Bra*_*don 9 javascript node.js async-await ecmascript-2017
我在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
}
Run Code Online (Sandbox Code Playgroud)
(之所以不async/await完全是因为顶级函数是一个任务队列库,表面上不能运行async/await样式)
如果etcFunction()抛出,error泡沫一直上升到顶层Promise吗?
如果没有,我怎么能冒泡errors?我需要每个包装await中try/catch并throw从那里,像这样?
async function doAnotherThing(data) {
try {
await etcFunction(data)
} catch(err) {
throw err
}
}
Run Code Online (Sandbox Code Playgroud)
如果
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
Run Code Online (Sandbox Code Playgroud)
一般来说,你的函数应该是这样的:
function toplevel(onsuccess, onerror) {
makePromise()
.then(doThing)
.then(onsuccess, onerror);
}
Run Code Online (Sandbox Code Playgroud)
没有不必要的函数表达式,没有.then(…).catch(…)反模式(可能导致onsuccess并onerror以这两个被称为)。
| 归档时间: |
|
| 查看次数: |
3304 次 |
| 最近记录: |