gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:26:53 28 4
gpt4 key购买 nike

我在 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com