首页  >  文章  >  web前端  >  解释 JavaScript 中的 Promise.allSettled() 和 async-await 吗?

解释 JavaScript 中的 Promise.allSettled() 和 async-await 吗?

WBOY
WBOY转载
2023-08-30 23:53:021160浏览

解释 JavaScript 中的 Promise.allSettled() 和 async-await 吗?

Promise.allSettled() 是一种方法,它采用可迭代的 Promise 作为参数,并返回一个 Promise,当可迭代中的所有 Promise 都已解决时,该 Promise 就被实现,这意味着它们已被实现或被拒绝。

当返回的 Promise 被履行时,它会通过包含有关已履行或拒绝的 Promise 的信息的对象数组来解析。每个对象都有一个状态属性(已完成或已拒绝),以及一个值或原因属性。

例如,如果您有一组代表网络请求的 Promise,并且想了解每个请求的状态(是否成功),则可以使用 Promise.allSettled() 等待所有请求完成在处理结果之前。

Promise.allSettled

当您想要处理多个 Promise 的结果时,无论它们是被履行还是被拒绝,使用 Promise.allSettled() 都会很有用。它与 Promise.all() 不同,Promise.all() 仅在所有 Promise 都满足时才会解决,如果任何 Promise 被拒绝,Promise.all() 就会拒绝。

语法

使用 Promise.allSettled() 的语法如下 -

Promise.allSettled(iterable);

Iterable 是提供给promise.allSettled() 的输入。可迭代对象是一个包含 Promise 的数组。

异步等待

JavaScript 中的 async 和await 关键字用于处理异步代码。 async 用在函数定义之前,表示该函数是异步的,并且将返回一个 Promise。

语法

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

await 用于异步函数内部以暂停执行,直到满足指定的 Promise。

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

Promise.allSetlled 与 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 作为输入。

  • 第 2 步 - 定义 validateForm() 函数,该函数将在提交表单时调用。

  • 第 3 步 - 在 validateForm() 函数内,使用 document.getElementById() 检索输入字段的值> 方法。

  • 第 4 步- 使用 validateInput() 函数创建验证承诺数组,并将输入字段值作为参数传递。

  • 第 5 步 - 使用 Promise.allSettled() 等待所有验证 Promise 完成。

  • 第 6 步 - 迭代 Promise.allSettled() 的结果并检查每个结果对象的 status 属性。如果任何 Promise 被拒绝,请将 hasErrors 标志设置为 true 并记录错误消息。

  • 第 7 步 - 如果 hasErrors 标志为 false,则表单被视为有效并可以提交。如果 hasErrors 标志为 true,则表单有错误,不应提交。

  • 第 8 步 - 将 onsubmit 属性添加到 HTML 表单中的 form 元素,并将其设置为调用 validateForm() 函数。如果 validateForm() 函数返回 false,请使用 return 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 的已完成值。

以上是解释 JavaScript 中的 Promise.allSettled() 和 async-await 吗?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除