【发布时间】:2022-01-22 21:30:08
【问题描述】:
我有一段代码在我的代码中重复了几次:函数:
exports.getCategoryProducts = (req, res) => {
db.collection("products")
.where("category", "==", req.params.category)
.limit(10)
.get()
//duplicate code starts
.then((data) => {
let products = [];
data.forEach((doc) => {
products.push({
id: doc.id,
title: doc.data().title,
category: doc.data().category,
description: doc.data().description,
image: doc.data().image,
price: doc.data().price,
rating: doc.data().rating,
});
});
return res.status(200).json(products);
})
.catch((err) => {
console.log(err);
return res.status(500).json({
message: "Something went wrong, please try again later",
});
});
//duplicate code ends
};
如何提取我标记的部分并将其用作其他 API 请求中的函数?
【问题讨论】:
-
您可以创建一个回调函数
cb来获取数据并在.then中执行所有操作。类似的错误。然后将其与.then(cb).catch(cbErr)一起使用 -
一个
.forEach()总是.push()es 数组中的东西应该是一个.map()
标签: javascript node.js promise