![](/img/trans.png)
[英]Why my async function doesn't await to the Promise in JavaScript?
[英]In javascript, why doesn't await return an error when a promise catches?
我喜歡 async/await,但我不明白為什么我們必須將 await 包裝在 try/catch 塊中以捕獲錯誤。 為什么不讓 await 返回某種類型的標准化錯誤 object 然后我們對此進行測試?
然后我們可以這樣做:
let results = await somePromise();
results?.err ? doSomething() : handleErr()
async/await
的要點是允許以更類似於同步代碼的方式編寫異步/基於承諾的代碼。 同步代碼使用try/catch
來處理異常,因此 按照最不意外的原則, await
也應該如此。
錯誤處理由作者決定。 如果您不控制某些拋出的代碼,並且希望它不拋出,請用捕獲但不拋出的東西包裝它。 在您自己的代碼中,您應該隨意返回錯誤對象而不是拋出。
請注意,其他人已經開始期望將 throw/catch 作為慣例。
// this one throws errors
import fnNotControlledByMe from 'external_lib'
// use this one as a wrapper, and don't throw
// this and any other function you write can opt not to throw
async function fnControlledByMe() {
try {
let results = fnNotControlledByMe();
return results;
} catch (err) {
return { err };
}
}
async function opFunction() {
let results = await fnControlledByMe();
results?.err ? doSomething() : handleErr()
}
為什么不讓
await
返回某種類型的標准化錯誤 object 然后我們對此進行測試?
因為這假設您總是想測試錯誤。 在許多(大多數)情況下,您不需要。 你想讓異常傳播。 這會導致大量樣板代碼(如帶有error
參數的節點回調模式)、被無知(無意識)的程序員忽略的錯誤以及重構風險。
正如@SeanSutherland 在他的回答中指出的那樣,這也使異步錯誤處理與同步錯誤處理對稱,具有相同的期望。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.