我無法理解在不觸發 Node 的情況下處理異步函式例外的正確方法UnhandledPromiseRejectionWarning(因為這似乎表明我做錯了什么)。
通常,在非異步代碼中,未處理的例外會一直冒泡到頂部并最終列印到控制臺。導致例外的代碼在堆疊中一直停止。
假設我有以下代碼:
test1().catch((e) => { throw e; });
console.log('got here top-level'); // This will print
async function test1() {
let test2Result = await test2();
console.log('got here test 1'); // This won't print
return test2Result;
}
async function test2() {
throw new Error('something failed here');
}
我希望這會做我想要的。在最頂層,它從異步函式中捕獲例外并重新拋出(但現在在任何異步代碼或 Promise 之外)。它應該仍然有原始堆疊跟蹤,所以我可以找到問題。快樂的日子,對吧?但是不,這仍然會導致UnhandledPromiseRejectionWarning,我不明白為什么。
從 Promise 中捕獲所有未處理例外的正確方法是什么?
uj5u.com熱心網友回復:
您的誤解來自此宣告...
從異步函式中捕獲例外并重新拋出(但現在在任何異步代碼或承諾之外)
Promise.prototype.catch()仍然是異步代碼。它回傳一個 Promise,就像.then()(實際上,.catch(onRejected)只是 的別名.then(undefined, onRejected))。
有趣的事實是,如果.catch()回呼沒有回傳一個被拒絕的承諾(例如Promise.reject())或throw,它回傳一個成功/已解決的承諾。
當您throw e在您.catch()的UnhandledPromiseRejectionWarning.
為了避免它,只需處理所有可能的承諾拒絕
test1().catch(console.error); // returns a resolved promise
// or
try {
await test1();
} catch (e) {
// consider this handled
}
uj5u.com熱心網友回復:
我通常會這樣做:
async function main() {
// do some async stuff here
await someAsyncWork();
}
let cc;
main()
.then( () => {
console.log('success!');
cc = 0 ;
}
.catch( e => {
console.error(e.stack);
cc = 1;
})
.finally( () => process.exit(cc) );
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/458720.html
標籤:javascript 节点.js 例外 异步等待
上一篇:處理變數但數量有限的引數
