13

我在脚本中有一个函数链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
}

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

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

如果没有,我怎么能冒泡errors?我是否需要像这样将每个都包装await在 atry/catchthrow从那里开始?

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

3 回答 3

6

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

是的。最外层函数返回的承诺将被拒绝。没有必要这样做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(…)反模式(可能导致onsuccessonerror同时调用)。

于 2016-11-28T16:59:27.030 回答
0

我知道这个问题很老,但是正如你的问题所写的那样,这个doAnotherThing()函数不是因为它只是包装就没有必要了etcFunction()吗?

所以你的代码可以简化为:

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

//Everything starts here...
topLevel()
于 2019-06-02T04:07:31.870 回答
0

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

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

于 2021-03-07T19:34:11.503 回答