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都被调用).

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...