我對節點的req, res
參數有點困惑,並且在我使用異步調用時處理這些參數的最佳方式。我目前擁有的一個功能應該是將一個Item添加到我的數據庫中,相應地更新一些數據庫模型,然後發送一個響應,說明更新已成功。但是,如果發生錯誤,該函數異步調用的函數可能會發送錯誤的響應。如果發生這種情況,我會收到錯誤Can't set headers after they are sent
,因爲我正在嘗試撥打res.send
兩次。希望得到某人的幫助,找出更好的處理錯誤的方法。謝謝!如何處理錯誤,而無需在node.js中設置res頭兩次
主要功能:
item.author = req.user._id;
item.description = req.query.description;
item.rating = req.query.rating;
item.save()
.then(result => {
// update user's items
UserController.updateItems(req.user._id, result._id);
ItemController.updateItemRating(req.query.outingId, req.query.rating, res);
res.send(result);
})
.catch(error => {
res.send(error);
});
updateItemRating:
export const updateItemRating = (itemId, rating, res) => {
Item.findOne({ _id: itemId }).exec((err, item) => {
if (item === undefined || item === null) {
return res.status(404).send('Item not found; check item ID');
}
Item.findOneAndUpdate(
{ _id: itemId },
{ $set: { rating: rating },
},
(error, item) => {
if (error) {
res.status(404).send('Error updating item with new rating');
}
});
});
};
updateItems:
export const updateItems = (userId, itemId) => {
User.findOneAndUpdate(
{ _id: userId },
{ $push: { items: [itemId] } },
(err, user) => {
console.log('user' + user);
if (err) {
console.log('got an error in updateItems');
}
});
};
您試圖執行'updateItemRating'作爲同步功能,而是**異步**功能。你應該鏈接承諾,然後最後使用一個'res.send'。或者使用**異步/等待** – Hosar