在我工作的公司里,一切都是用回调完成的。我们正在开始编写具有大代码所依赖的承诺的小组件。我们开始遇到麻烦。如何用回调包装承诺?
function getSomething() {
return Promise.resolve('hello')
}
function test(cb) {
getSomething()
.then(string => {
a.s
cb(null, string)
}, error => cb(error))
}
test((error, result) => {
console.log(error)
console.log(result)
a.s
})
这是一个简单的问题示例。在这个代码中,因为a不存在,它会抛出一个警告UnhandledPromiseRejectionWarning并终止进程。控制台日志永远不会到达。
背后的逻辑是,如果发生错误会触发catch回调。
function test(cb) {
getSomething()
.then(string => {
// a.s
cb(null, string)
}, error => cb(error))
.catch(error => cb(error))
}
我被建议在承诺链的末尾使用显式捕获。问题是如果在回调中抛出一个错误,回调会触发两次。
感谢您的任何帮助。
如何整个包住再放入一试,并在catch错误? –
那么..那么可能你不应该在'then'阶段使用'onRejected'回调,而只需链接一个'.catch()'就像你在第二个代码段中做的那样。 – Redu
@Redu,将此评论移至答案,因为这是正确的答案。 @ AlvaroOrtiz的第二段代码将错误处理程序'cb'连接两次。 – DaveS