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

时间:2016-11-28 16:37:42

标签: javascript node.js async-await ecmascript-2017

我在node 4.3脚本中有一个类似于回调的功能链 - >承诺 - > 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的原因是顶级函数是一个任务队列库,表面上不能运行async/await样式)

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

如果没有,我该如何冒泡errors?我是否需要将每个await包裹在try/catchthrow中,如此?

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

3 个答案:

答案 0 :(得分:4)

  

如果etcFunction()抛出,错误会在async function s中一直冒出来吗?

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

  

......一路冒泡到最高级别的Promise?

没有。您的topLevel包含多个错误。如果你没有return来自doThing(data)回调的then,它将被忽略(甚至没有等待)并且拒绝仍未处理。你必须使用

.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(可能导致onsuccessonerror 两者被调用。)

答案 1 :(得分:0)

我知道这个问题很旧,但是正如您写的问题一样,doAnotherThing()函数不是不必要的,因为它只包装了etcFunction()

因此您的代码可以简化为:

async function topLevel(){
  let thing = await doThing(data)
  let thingDone = await etcFunction(data)
  //Everything is done here...
}

//Everything starts here...
topLevel()

答案 2 :(得分:0)

我刚刚遇到了一个类似的问题,我的嵌套错误似乎没有冒泡到我的顶级函数。

我的解决方法是从我的嵌套函数中删除“try/catch”并允许抛出错误。

相关问题