如何在then()方法内发送响应,然后再发送另一个then()方法?
exports.confirm_new_app = (req, res) => {
//get the app
AppReq.findOne({_id: req.body.appId})
.then( (app) => {
if (app) {
//remove additional info(reqDate,reqUserId)
app = app.toObject()
delete app.reqDate
delete app.reqUserId
//add it to apps collection
let newApp = new App(app)
return newApp.save()
} else {
//how to send this response??????
res.status(404).json({
message: "No application with the provided app Id!"
})
}
})
.then( (savedApp) => {
//remove the savedApp from appReq collection
return AppReq.remove({_id: savedApp._id})
}).then( (removedApp) => {
res.status(200).json(removedApp)
})
.catch( (err) => {
res.status(500).json({
error: err
})
})
}
在以上示例中,发送res.status(404).json({...})
的正确方法是什么?当前代码将触发错误,因为它尝试发送两次响应!
如果有错误并想退出.then()
链,则抛出错误。然后处理您的捕获中的错误。
所以代替
else {
//how to send this response??????
res.status(404).json({
message: "No application with the provided app Id!"
})
}
尝试:
else {
throw new Error('appId');
}
然后抓住了:
.catch( (err) => {
if (err.message === 'appId') {
res.status(404).json({
message: "No application with the provided app Id!"
})
} else {
res.status(500).json({
error: err
})
}
})