13

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ますか? そのように、そこからandでそれぞれawaitをラップする必要がありますか?try/catchthrow

async function doAnotherThing(data) {
   try {
     await etcFunction(data)
   } catch(err) {
     throw err  
   }
}
4

3 に答える 3

6

etcFunction()がスローされた場合、エラーはasync functions までバブルアップしますか?

はい。最も外側の関数によって返される promise は拒否されます。する必要はありません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

一般に、関数は次のようになります。

function toplevel(onsuccess, onerror) {
    makePromise()
    .then(doThing)
    .then(onsuccess, onerror);
}

不要な関数式やアンチ.then(…).catch(…)パターン(両方が呼び出される可能性がある)はありません。onsuccessonerror

于 2016-11-28T16:59:27.030 に答える