1 回答
TA貢獻1829條經驗 獲得超4個贊
問題在于,res.status當您return res.status(/*...*/)從then回調中執行操作時,該鏈會繼續使用作為履行值的返回值。
您不能為此使用單個鏈。此外,由于您需要同時定位用戶和產品,因此最好并行執行該操作。見評論:
// *** Start both the product and user search in parallel
Promise.all([
User.findById(req.params.userId).exec(),
Product.findById(req.params.productId).exec()
])
.then(([user, product]) => {
// *** Handle it if either isn't found
if (!user) {
res.status(404).json({
message: 'User not found'
});
} else if (!product) {
res.status(404).json({
message: 'Product not found'
});
} else {
// *** Both found, do the review
const review = new Review({
_id: mongoose.Types.ObjectId(),
rev: req.body.rev,
productId: req.params.productId,
userId: req.params.userId
});
// *** Return the result of the save operation
return review.save()
.then(response => {
console.log("responseeeeeeee", response);
res.status(201).json({
response
});
}
}
// *** Implicit return of `undefined` here fulfills the promise with `undefined`, which is fine
})
.catch(error => {
// *** An error occurred finding the user, the product, or saving the review
console.log("error", error);
res.status(500).json({
error
})
});
如果您在任何現代版本的 Node.js 中執行此操作,您可以使用async函數和await:
// *** In an `async` function
try {
const [user, product] = await Promise.all([
User.findById(req.params.userId).exec(),
Product.findById(req.params.productId).exec()
]);
if (!user) {
res.status(404).json({
message: 'User not found'
});
} else if (!product) {
res.status(404).json({
message: 'Product not found'
});
} else {
// *** Both found, do the review
const review = new Review({
_id: mongoose.Types.ObjectId(),
rev: req.body.rev,
productId: req.params.productId,
userId: req.params.userId
});
const response = await review.save();
console.log("responseeeeeeee", response);
res.status(201).json({
response
});
}
} catch (error) {
console.log("error", error);
res.status(500).json({
error
})
}
請注意,整個代碼包裝在一個try/ catch,所以async功能這是永遠都不會拒絕(除非console.log或res.send在catch塊中引發錯誤),這樣就不會導致未處理拒絕警告,如果你只是讓你Express端點處理程序async(而通常將async函數傳遞給不希望收到承諾的東西是一種反模式)。(如果您想有點偏執,請將catch塊的內容包裝在另一個try/ 中catch。)
添加回答
舉報
