微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 从嵌套的async / await函数中捕获错误

我在节点4.3脚本中有一个函数链,看起来像callback – >承诺 – > async / await – > async / await – >异步/ AWAIT

像这样:

const topLevel = (resolve,reject) => {
    const foo = doThing(data)
    .then(results => {
        resolve(results)
    })
    .catch(err => {
        reject(err)
    })
}

async function doThing(data) {
    const thing = await doAnotherThing(data)
    return thing
}

async function doAnotherThing(data) {
    const thingDone = await etcFunction(data)
    return thingDone
}

(它不是异步/等待一直是因为顶级函数一个任务队列库,表面上不能运行async / await样式)

如果etcFunction()抛出,错误是否一直冒泡到顶级Promise?

如果没有,我怎么能冒出错误?我是否需要在try / catch中包装每个等待并从那里抛出,就像这样?

async function doAnotherThing(data) {
   try {
     await etcFunction(data)
   } catch(err) {
     throw err  
   }
}

解决方法

If etcFunction() throws,does the error bubble up all the way through the async functions?

是.最外层函数返回的承诺将被拒绝.没有必要尝试{…} catch(e){throw e;这和同步代码一样毫无意义.

… bubble up all the way to the top-level Promise?

不.您的topLevel包含多个错误.如果你没有从当时的回调中返回doThing(数据),它将被忽略(甚至没有等待)并且拒绝保持未处理状态.你必须使用

.then(data => { return doThing(data); })
// or
.then(data => doThing(data))
// or just
.then(doThing) // recommended

通常,您的函数应如下所示:

function toplevel(onsuccess,onerror) {
    makePromise()
    .then(doThing)
    .then(onsuccess,onerror);
}

没有不必要的函数表达式,没有.then(…).catch(…) antipattern(这可能导致onsuccess和onerror都被调用).

原文地址:https://www.jb51.cc/js/156819.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐