使用await時用catch處理Promise拒絕
在JavaScript中,使用者可以使用Promise執行特定操作。例如,我們可以建立Promise來使用API從資料庫中獲取資料。如果Promise成功從資料庫獲取資料,則表示Promise成功;如果Promise出現錯誤,則表示Promise被拒絕。
讓我們先看看建立Promise的語法。
語法
使用者可以按照以下語法在JavaScript中建立Promise。
let testPromise = new Promise((res, rej) => { // perform some operation });
在上面的語法中,我們使用了`Promise()`建構函式和`new`關鍵字來建立一個Promise。
示例
在下面的示例中,我們建立了兩個不同的Promise。此外,我們還解決了並拒絕了它們。
使用者可以在下面的程式碼中看到我們如何管理`testPromise1`,因為它已成功解決。邏輯部分包含第二個Promise,我們需要使用catch塊來處理錯誤。在輸出中,使用者可以觀察到`testPromise2`的Promise訊息是從catch塊打印出來的。
<html> <body> <h2><i>Promise</i> in JavaScript</h2> <p id = "output"> </p> <script> let output = document.getElementById("output"); // Creating the promise and resolving it let testPromise1 = new Promise((res, rej) => { res("The testPromise1 is resolved successfully!"); }); // rejecting the promise let testPromise2 = new Promise((res, rej) => { rej("The testPromise2 is Rejected due to error!"); }); // execute the testPromise1 testPromise1.then((res) => { output.innerHTML += res; output.innerHTML += "</br>"; }); //execute the testPromise2, and use the catch block to handle errors. testPromise2 .then((res) => { output.innerHTML += res; }) .catch((error) => { output.innerHTML += "Inside the catch block for testPromise2. </br>"; output.innerHTML += error; }); </script> </body> </html>
將Promise與非同步函式和await關鍵字一起使用
使用者已經學習瞭如何建立Promise。還學習瞭如何使用catch塊處理已解決和已拒絕的Promise。
現在,我們將學習如何將Promise與非同步函式和await關鍵字一起使用。因此,我們必須使用try-catch塊來處理來自已拒絕Promise的錯誤。
非同步函式允許我們在程式中並行執行多個任務。我們可以使用`async`關鍵字定義函式以使其成為非同步函式。之後,我們可以在函式內部使用`await`關鍵字來等待Promise結果。有時,在沒有從Promise獲取結果的情況下,我們無法在函式中執行其他任務。因此,我們必須等待結果,這可以透過使用`await`關鍵字來實現。
語法
使用者可以按照以下語法使用try-catch塊來處理在將Promise與await關鍵字一起使用時出現的Promise錯誤。
async function executePromise() { try { // call the promise, and wait until it is fulfilled! await promise1(); } catch (error) { // if the promise is rejected, control comes here } }
在上面的語法中,我們使用了`async`關鍵字使函式非同步化,並使用`await`關鍵字等待Promise完成或被拒絕。
示例
在下面的示例中,我們建立了非同步函式。此外,我們還建立了`promise1()`函式,該函式返回一個被拒絕的Promise。在非同步函式中,我們使用await關鍵字呼叫了`promise1()`函式,並且由於Promise被拒絕,控制權轉到catch塊。
<html> <body> <h3>Handling the <i>Promise rejection using catch block</i> While using await keyword in JavaScript.</h3> <p id = "output"> </p> <script> let output = document.getElementById("output"); // rejecting the promise let Promise1 = () => { return new Promise((res, rej) => { rej(new Error(400)); }); }; async function executePromise() { try { // call the promise, and wait until it is fulfilled! await Promise1(); } catch (error) { output.innerHTML += "Promise is rejected, and an error message is " + error.message; } } executePromise(); </script> </body> </html>
示例
在下面的示例中,我們建立了與我們在上面示例中建立的相同的Promise,但是我們在拒絕Promise時添加了計時器。
當用戶單擊“執行Promise”按鈕時,它將執行`executePromise()`函式。在`executePromise()`函式中,我們使用await關鍵字呼叫`timerPromise()`,`timerPromise()`在5秒內拒絕Promise,並且在此之前函式等待繼續執行。
<html> <body> <h3>Handling the <i>Promise rejection using catch block</i> While using await keyword and timer in JavaScript. </h3> <p> Click on the "Execute promise" button and wiat for 5 seconds </p> <p id = "output"> </p> <button onClick = "executePromise()"> Execute promise </button> <script> let output = document.getElementById("output"); // rejecting the promise let timerPromise = () => { return new Promise((res, rej) => { setTimeout( () => rej(new Error("Promise is rejected after 5 seconds")), 5000 ); }); }; async function executePromise() { try { // function will not move ahead until the promise is fulfilled. await timerPromise(); } catch (error) { output.innerHTML += "Promise is rejected, and an error message is " + error.message; } } </script> </body> </html>
在上面的輸出中,使用者可以觀察到,當他們單擊“執行Promise”按鈕後,5秒鐘後,他們會看到來自catch塊的錯誤訊息,因為Promise需要5秒鐘才能被拒絕。