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

Bra*_*don 9 javascript node.js async-await ecmascript-2017

我在node 4.3脚本中有一个函数链,类似于回调 - >承诺 - > async/await - > async/await - > async/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
}
Run Code Online (Sandbox Code Playgroud)

(之所以不async/await完全是因为顶级函数是一个任务队列库,表面上不能运行async/await样式)

如果etcFunction()抛出,error泡沫一直上升到顶层Promise吗?

如果没有,我怎么能冒泡errors?我需要每个包装awaittry/catchthrow从那里,像这样?

async function doAnotherThing(data) {
   try {
     await etcFunction(data)
   } catch(err) {
     throw err  
   }
}
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 6

如果etcFunction()抛出,错误会一直冒泡到async functions 中吗?

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

……一直冒泡到顶级Promise?

不。您topLevel包含多个错误。如果不这样做returndoThing(data)then回调,它将被忽略(甚至没有等待),并拒绝入住未处理。你必须使用

.then(data => { return doThing(data); })
// or
.then(data => doThing(data))
// or just
.then(doThing) // recommended
Run Code Online (Sandbox Code Playgroud)

一般来说,你的函数应该是这样的:

function toplevel(onsuccess, onerror) {
    makePromise()
    .then(doThing)
    .then(onsuccess, onerror);
}
Run Code Online (Sandbox Code Playgroud)

没有不必要的函数表达式,没有.then(…).catch(…)反模式(可能导致onsuccessonerror这两个被称为)。