使用 async-await 解釋 JavaScript 中的 Promise.allSettled()?


Promise.allSettled() 是一種方法,它接受一個 Promise 的可迭代物件作為引數,並返回一個 Promise,當可迭代物件中的所有 Promise 都已完成(settled)時,該 Promise 就會 fulfilled。所謂完成,意味著它們要麼 fulfilled 要麼 rejected。

當返回的 Promise fulfilled 時,它會解析為一個包含有關 fulfilled 或 rejected Promise 的資訊的陣列物件。每個物件都有一個 status 屬性,值為 fulfilled 或 rejected,以及一個 value 或 reason 屬性,分別表示值或原因。

例如,如果您有一個代表網路請求的 Promise 陣列,並且想要了解每個請求的狀態(成功與否),您可以使用 Promise.allSettled() 等待所有請求完成,然後再處理結果。

Promise.allSettled

當您想要處理多個 Promise 的結果時,無論它們是 fulfilled 還是 rejected,使用 Promise.allSettled() 都很有用。它與 Promise.all() 不同,Promise.all() 只有在所有 Promise 都 fulfilled 時才會 resolve,如果任何一個 Promise rejected 就會 reject。

語法

使用 Promise.allSettled() 的語法如下所示:

Promise.allSettled(iterable);

Iterable 是傳遞給 promise.allSettled() 的輸入。iterable 物件是一個包含 Promise 的陣列。

Async-await

JavaScript 中的 async 和 await 關鍵字用於處理非同步程式碼。async 用於函式定義之前,表示該函式是非同步的,並將返回一個 Promise。

語法

async function example() {
   // asynchronous code goes here
}

await 用於 async 函式內部,暫停執行,直到指定的 Promise fulfilled。

async function example() {
   const result = await somePromise;
   // the rest of the function will execute only after somePromise is fulfilled
}

Promise.allSettled 與 async-await

async/await 語法是一種使非同步程式碼看起來和行為更像同步程式碼的方式,從而使其更易於閱讀和編寫。它允許您編寫看起來和感覺類似於同步程式碼的非同步程式碼,而無需使用回撥或 then() 方法。

您可以使用 async/await 語法等待 Promise.allSettled() 方法解析,然後再訪問結果。

以下是如何使用 Promise.allSettled() 與 async/await 的示例:

async function example() {
   const promises = [promise1, promise2, promise3];
   const results = await Promise.allSettled(promises);
   for (const result of results) {
      if (result.status === 'fulfilled') {
         console.log(result.value);
      } else {
         console.error(result.reason);
      }
   }
}

以下是 Promise.allSettled() 在現實世界中可能存在的兩種用例

  • 處理網路請求

  • 處理表單中的使用者輸入

示例 1

如果您有一個網路請求陣列(例如 HTTP 請求),並且您想要處理所有請求的結果,無論它們是否成功,都可以使用 Promise.allSettled() 等待所有請求完成,然後再處理結果。

<html>
<body>
   <h2> Using the <i> Promise.allSettled() </i> method to handle multiple reuests. </h2>
   <button onclick = "getData()"> Fetch Data </button>
   <div id = "output"> </div>
   <script>
      async function getData() {
         const requests = [
            fetch('https://jsonplaceholder.typicode.com/todos/1'),
            fetch('https://jsonplaceholder.typicode.com/todos/2'),
            fetch('https://jsonplaceholder.typicode.com/todos/3')
         ];
         const results = await Promise.allSettled(requests);
         let output = '';
         let count = 0;
         for (const result of results) {
            if (result.status === 'fulfilled') {
               const data = await result.value.json();
               output += `<p>Promise ${count+1 } fulfilled</p>`;
            } else {
               output += `<p>Promise ${count+1} rejected </p>`;
            }
            count++
         }
         document.getElementById('output').innerHTML = output;
      }
   </script>
</body>
</html>

假設您有一個帶有輸入欄位的表單,並且您希望在提交表單之前驗證所有欄位。在這種情況下,您可以使用 Promise.allSettled() 等待所有驗證 Promise 完成,然後再決定是否提交表單。

以下是需要遵循的步驟

  • 步驟 1 − 在 HTML 文件中,編寫一個帶有輸入欄位的表單。將其 id 設定為 input。

  • 步驟 2 − 定義validateForm() 函式,該函式將在提交表單時呼叫。

  • 步驟 3 − 在validateForm() 函式內部,使用document.getElementById() 方法檢索輸入欄位的值。

  • 步驟 4 − 使用validateInput() 函式建立一個驗證 Promise 陣列,並將輸入欄位值作為引數傳遞。

  • 步驟 5 − 使用Promise.allSettled() 等待所有驗證 Promise 完成。

  • 步驟 6 − 遍歷Promise.allSettled() 的結果,並檢查每個結果物件的 status 屬性。如果任何 Promise 被 rejected,則將 hasErrors 標誌設定為 true 並記錄錯誤訊息。

  • 步驟 7 − 如果 hasErrors 標誌為 false,則表單被認為有效,可以提交。如果 hasErrors 標誌為 true,則表單存在錯誤,不應提交。

  • 步驟 8 − 在 HTML 表單中的表單元素中新增 onsubmit 屬性,並將其設定為呼叫validateForm() 函式。使用 return false 語句來防止在validateForm() 函式返回 false 時提交表單。

示例 2

<html>
   <h2> Using Promise.allSettled with async-await </h2>
   <form onsubmit = "validateForm(); return false;">
   <label for = "input">Input:</label> <input type = "text" id = "input" required>
   <br><br><input type = "submit" value = "Submit"></form>
   <p id = "output"></p>
   <script >
      function validateInput(input) {
         return new Promise((resolve, reject) => {
            if (input.length > 0) {
               resolve();
            } else {
               reject(new Error('Input is required'));
            }
         });
      }
      async function validateForm() {
         const input = document.getElementById('input').value;
         const validationPromises = [
            validateInput(input),
         ];
         const results = await Promise.allSettled(validationPromises);
         let hasErrors = false;
         for (const result of results) {
            if (result.status === 'rejected') {
               hasErrors = true;
               console.error(result.reason);
            }
         }
         if (!hasErrors) {
            // form is valid, submit it
            document.getElementById("output").innerHTML="Form Submitted Successfully";
         } else {
            // form has errors, do not submit it
            document.getElementById("output").innerHTML = 'Form has errors';
         }
      }
   </script>
</html>

Promise.allSettled() 可用於各種情況,例如處理網路請求和驗證使用者輸入,並且可以與 async/await 語法或 then() 方法結合使用以處理 Promise 的 fulfilled 值。

更新於: 2022-12-29

7K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.