我有下面的代碼:的JavaScript塊流執行承諾
router.post('/', function(req, res, next) {
doAsyncStuff()
.then(ret=>{
console.log('first then block')
if (/*something*/)
res.sendStatus(202); /*I want to stop the execution here. changing this in return res.sendstatus will not solve the problem*/
else
return doanotherAsyncStuff() /*i could move the second then block here but i need another catch statment*/
})
.then(ret=>{
console.log('second then block');
res.sendStatus(200)
})
.catch(err=>{
console.log(err)
err.status = 503
next(err)
})
});
我的問題是,當我if
表達是真實的,我想打電話給res.sendstatus(202)
和停止執行流程。但是我的代碼沒有做我想做的事情,因爲即使我的if
表達式爲真,「second then block」仍然會被記錄下來。
我可以將第二個then
塊移動到第一個塊中,在調用doanotherAsyncStuff()
方法之後,但如果我這樣做,我需要另一個catch語句,並且我想只有一個catch語句任何調用的異步方法都會發生錯誤。
所以我的問題是:當我的if
表達式爲真時,有沒有辦法阻止承諾流執行?