【发布时间】:2016-03-30 15:28:42
【问题描述】:
假设我有 4 个函数:runA()、runB()、runC() 和 runD()。
使用 ES6 承诺,在完全成功的运行中,这些都将一个接一个地运行:
runA()
.then(runB)
.then(runC)
.then(runD)
如果runA 或runB 失败(拒绝或抛出),我想调用error1() 然后完全停止链(而不是调用runC 或runD)。这让我觉得我应该在.then 承诺链的最后添加一个.catch():
runA()
.then(runB)
.then(runC) //won't get called if runA or runB throws
.then(runD) //won't get called if runA or runB throws
.catch(error1)
但如果runC 失败,我想调用error2() 并仍然停止链(而不是调用runD)。
runA()
.then(runB)
.catch(error1) //moved up to only handle runA and runB
.then(runC) //but now this gets called after error1() is run
.then(runD)
.catch(error2)
现在我在链中有 2 个 catch 调用,runC 将在 error1 运行后被调用,因为捕获的结果将默认为 resolve。让error1 函数创建一个它总是拒绝的承诺是我唯一的选择吗?
【问题讨论】:
-
只使用一个
.catch()有什么问题?您可以在 catch 回调 (if (error1) error1() else if (error2) error2()...) 中进行错误分类。您抛出的Error对象可以包含消息和名称(可以是您需要的类型,例如“RunCError”)。 -
当然,您的意思是
runA() .then(runB) .then(runC) .then(runD)- ...除此之外,如果您真的无法确定导致错误的原因,您可以在最后throwerror1跳过runC和runD- 但您需要在error2中确定错误来自 A 或 B 而不是 C 或 D