簡體   English   中英

如何調用 catch() 方法“嘗試捕獲”promise 的異常?

[英]How can calling a catch() method "try catch" the exception of a promise?

換句話說,我們通常不能簡單地通過調用另一個方法來“嘗試捕獲”異常。

但是我們可以通過以下方式處理 promise 的異常

promise
  .then()
  .catch();

或者

promise
  .then(fulfillmentHandler, rejectionHandler);

如果第一種情況下的promise.then()拋出異常,那么如何在該 promise 上調用catch()方法來處理之前發生的異常?

我們通常必須通過使用包裝它來處理異常

try {
  // doSomething
} catch (err) {
  // handle the error
}

因此,如果then()返回的 promise 發生異常, then()promise.then()運行時代碼是否必須處理異常? 簡單地調用對象上的方法通常無法處理其異常(在這種情況下,在then()返回的承諾上調用catch() ),因為沒有這樣的包裝?

你能做的最好的事情就是查找一些 promise polyfill。

任何傳遞給promise 的函數,在構造函數中或在.then有一個回調在內部包裝在try-catch 中,如果此函數拋出,它將觸發下一個.catch (或拋出未處理的promise 拒絕錯誤)。

然而,在 try-catch 中包裝 promise 不會捕獲未處理的拒絕,因為它們有些特殊。 要抓住它們,您必須使用它:( 參考

window.addEventListener('unhandledrejection', function(event) {
    console.error(`Unhandled rejection (promise: ${event.promise}, reason: ${event.reason}).`);
});

如果then()返回的 promise 發生異常, then()promise.then()運行時代碼是否必須處理異常?

then返回的 Promise 中發生的異常還沒有發生,它只會發生在那個 Promise 的微任務中,在主任務完成后。

 Promise.resolve() .then( callback ) // still synchronously in the main task, no error yet .catch( console.error ); console.log( "done with main task" ); // this will only get executed in a micro-task, when the main task is done function callback() { console.log( "will now throw" ); throw new Error( "not good" ); }

因此這些.catch() .then().catch()返回的 Promise 對象將能夠很好地附加回調,並且主任務中的任何內容都不會拋出。



唯一可能令人困惑的是 Promise 構造函數,它將同步包裝異常:

 const promise = new Promise( () => { console.log( "will now throw" ); throw new Error( "not good" ); } ); console.log( "yet here we are fine" );

但這與 Events 並沒有什么不同:

 addEventListener( 'test', e => { console.log( "will now throw" ); throw new Error( "not good" ); } ); dispatchEvent( new Event( "test" ) ); console.log( "Yet we are fine" );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM