Javascript 多级承诺Node.js中抛出链错误
我想将不同级别的承诺中出现的不同错误链接起来,并在最后一次捕获中出现一个错误 假设我们有以下情况:Javascript 多级承诺Node.js中抛出链错误,javascript,node.js,promise,try-catch,Javascript,Node.js,Promise,Try Catch,我想将不同级别的承诺中出现的不同错误链接起来,并在最后一次捕获中出现一个错误 假设我们有以下情况: this.methodOne().then( responseOne =>{ this.methodTwo(responseOne ).then( responseTwo =>{ console.log(responseTwo ); }).catch(err => { // send err to last catch t
this.methodOne().then( responseOne =>{
this.methodTwo(responseOne ).then( responseTwo =>{
console.log(responseTwo );
}).catch(err => {
// send err to last catch
throw err;
})
}).catch(err => {
// Show err one or two
console.log(err)
})
但它不起作用
谢谢您必须返回内部承诺,以便
抛出
进行传播。只有当您从.then()
处理程序返回内部承诺时,才会将其添加到链中。当您这样做时,它们被插入到链中,它们的已解决或拒绝状态就是外部承诺链得到的状态。没有返回
,内部承诺链只是它自己的独立承诺链,根本不连接到外部承诺链
因此,改变这一点:
this.methodOne().then( responseOne =>{
this.methodTwo(responseOne ).then( responseTwo =>{
console.log(responseTwo );
}).catch(err => {
// send err to last catch
throw err;
})
}).catch(err => {
// Show err one or two
console.log(err)
})
为此:
this.methodOne().then(responseOne => {
// ADD return on next line to return inner promise
// to add this inner promise chain to the outer chain
return this.methodTwo(responseOne ).then(responseTwo => {
console.log(responseTwo );
return responseTwo; // return this so it becomes the resolved
// value of parent chain too
}).catch(err => {
// send err to last catch
throw err;
});
}).catch(err => {
// Show err one or two
console.log(err)
})
@BorisDetry-因为看起来您可能是新来的,如果这回答了您的问题,您可以通过单击答案左侧的复选标记向社区表明这一点。这也将为您在网站上按照正确的程序赢得一些声誉点数。通常,只有在以下情况下才需要内部捕获:(a)您想要检查错误(记住重新抛出错误)(b)您想要注入自定义错误消息(更改error.message并重新抛出,或抛出新错误)(c)您希望注入一个默认值来代替应该传递到成功路径的内容(返回该值)。否则,不要接住。