【发布时间】:2017-04-12 11:15:46
【问题描述】:
我在 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 包装在try/catch 和throw 中吗?
async function doAnotherThing(data) {
try {
await etcFunction(data)
} catch(err) {
throw err
}
}
【问题讨论】:
-
什么是
makePromise? -
"顶层函数是一个任务队列库,表面上不能以异步/等待方式运行" - 队列库没有理由不能使用
async functions 作为任务。你真的不应该处理回调。如果您需要使用采用回调样式的特定队列库,请使用包装函数。 -
@Bergi
makePromise实际上是一个async函数,但由于它是从非async环境调用的,所以我将其视为承诺。回复:我同意,我最终会尝试并承诺它,但我可以同时有可靠的错误冒泡吗? -
@Bergi 我从 sn-p 中删除了
makePromise位以澄清——顶层调用的第一个函数是async function,我将其视为常规Promise -
@Bergi 是的,感谢您发现该错误和其他错误-我应该只是复制实际代码而不是尝试用伪代码重新创建
标签: javascript node.js async-await ecmascript-2017