首頁 > web前端 > js教程 > 主體

在 JavaScript 中使用 wait 時透過 catch 處理 Promise 拒絕

WBOY
發布: 2023-08-24 16:57:02
轉載
1257 人瀏覽過

在 JavaScript 中使用 wait 时通过 catch 处理 Promise 拒绝

在 JavaScript 中,使用者可以使用 Promise 執行特定操作。例如,我們可以建立使用 API 從資料庫取得資料的 Promise。如果 Promise 成功從資料庫取得數據,則表示 Promise 成功,否則 Promise 出錯,則表示 Promise 被拒絕。

讓我們先來看看建立 Promise 的語法。

文法

使用者可以依照下列語法在 JavaScript 中建立 Promise。

let testPromise = new Promise((res, rej) => {
   
   // perform some operation
});
登入後複製

在上面的語法中,我們使用帶有「new」關鍵字的 Promise() 建構子來建立 Promise。

範例

在下面的範例中,我們建立了兩個不同的 Promise。此外,我們已經解決並拒絕了它們。

用戶可以在下面的程式碼中看到我們如何管理 testPromise1,因為它已成功解決。邏輯部分附帶第二個承諾,即我們需要使用 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關鍵字結合使用

使用者已經學會了創造承諾。此外,還學會了使用 catch 區塊處理已解決和拒絕的承諾。

現在,我們將學習使用帶有非同步函數和await關鍵字的promise。因此,我們必須使用 try-catch 區塊來處理被拒絕的 Promise 中的錯誤。

非同步函數允許我們在程式中並行執行多個任務。我們可以定義函數後面跟著async關鍵字以使其非同步。之後,我們可以在函數內使用await關鍵字來等待promise結果。有時,如果沒有從 Promise 中獲得結果,我們就無法在函數中執行其他任務。因此,我們必須等待使用 await 關鍵字可以獲得的結果。

文法

當我們使用帶有await關鍵字的promise時,使用者可以按照下面的語法使用try-catch區塊來處理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() 函數,它傳回一個帶有拒絕的承諾。在非同步函數中,我們使用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 時添加了計時器。

當使用者點選「execute Promise」按鈕時,它會執行executePromise()函數。在executePromise()函數中,我們使用await關鍵字呼叫timerPromise(),並且timerPromise()拒絕承諾直到5秒,直到函數等待繼續前進。

<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 秒才能被拒絕。

以上是在 JavaScript 中使用 wait 時透過 catch 處理 Promise 拒絕的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!