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

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

我在 node 4.3 脚本中有一个函数链,类似于回调 -> promise -> 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 包装在 try/catchthrow 中吗?

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?

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

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

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

.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 (这可能导致 onsuccessonerrorboth 被调用)。

关于javascript - 从嵌套的 async/await 函数中捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40849282/

相关文章:

node.js - laravel5 的 yeoman 生成器 - composer create-project 的问题

c# - 使用 ASP.NET MVC 异步 Controller 方法处理多个用户请求

c# - 单元测试 async void 事件处理程序

javascript - 如何将名称中包含空格的 json 值与变量绑定(bind)

javascript - 滚动表格时固定表格内的标题

javascript - 如何在 JavaScript canvas 中为透明 PNG 图像添加描边/轮廓

javascript - 在react-native中运行之前,如何让应用程序等待从从firestore获取数据的模块获取所有数据?

javascript - 在 mustache 模板中通过数组键选择项目?

javascript - 使用 Node 的 http 模块服务 angular.min.js

javascript - 我可以告诉浏览器同步始终使用一个 .html 文件吗? (对于 html5mode 链接)