【发布时间】:2018-02-27 23:47:36
【问题描述】:
我的代码是这样的:
router.post("/", (req, res, next) => {
foo()
.then((result) => {
res.send(result)
})
.catch((error) => {
cosnole.log(error)
})
//I only want the bar() function and everything below it to run if the first promise is rejected and the first .catch function ran
bar()
.then((data) => {
res.send(data)
})
.catch((error) => {
console.log(error)
})
})
我只想在第一个 promise 被拒绝并且 .catch 函数触发时才运行 bar() 函数和 .then .catch 函数。
我试过了:
router.post("/", (req, res, next) => {
rejected = false
foo()
.then((result) => {
res.send(result)
})
.catch((error) => {
rejected = true
console.log(error)
})
if(rejected == true)
bar()
.then((data) => {
res.send(data)
})
.catch((error) => {
console.log(error)
})
})
但是当第一个 foo() 函数的错误被捕获并且 promise 被拒绝时,bar() 函数永远不会被执行。
【问题讨论】:
-
你的 if 代码在 then() 得到解决之前已经执行
标签: javascript asynchronous ecmascript-6 promise es6-promise