Home > Web Front-end > JS Tutorial > body text

Explain Promise.allSettled() and async-await in JavaScript?

WBOY
Release: 2023-08-30 23:53:02
forward
1233 people have browsed it

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

Promise.allSettled() is a method that takes an iterable of Promises as a parameter and returns a Promise that is resolved when all Promises in the iterable have been resolved are realized, which means they have been realized or rejected.

When the returned Promise is fulfilled, it is resolved through an array of objects containing information about the fulfilled or rejected Promise. Each object has a status attribute (Complete or Rejected), and a value or reason attribute.

For example, if you have a set of Promises that represent network requests, and you want to know the status of each request (whether it was successful or not), you can use Promise.allSettled() to wait for all requests to complete before processing the result.

Promise.allSettled

Using Promise.allSettled() is useful when you want to handle the results of multiple Promises, whether they were fulfilled or rejected. It differs from Promise.all() which will only resolve when all Promises are satisfied and will reject if any Promise is rejected.

grammar

The syntax for using Promise.allSettled() is as follows -

Promise.allSettled(iterable);
Copy after login

Iterable is the input provided to promise.allSettled(). Iterable object is an array containing Promises.

Asynchronous wait

The async and await keywords in JavaScript are used to handle asynchronous code. async is used before a function definition to indicate that the function is asynchronous and will return a Promise.

grammar

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

await is used inside an asynchronous function to pause execution until a specified Promise is met.

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

Promise.allSetlled and async-await

The async/await syntax is a way to make asynchronous code look and behave more like synchronous code, making it easier to read and write. It allows you to write asynchronous code that looks and feels like synchronous code without the need for callbacks or then() methods.

You can use async/await syntax to wait for the Promise.allSettled() method to resolve before accessing the result.

This is an example of using Promise.allSettled() with 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);
      }
   }
}
Copy after login

The following are two possible use cases for Promise.allSettled() in the real world:

  • Handling network requests

  • Handling user input in forms

Example 1

If you have an array of network requests (such as HTTP requests) and you want to handle the results of all requests, regardless of whether they were successful, you can use Promise.allSettled() to wait for all requests to complete before processing the results.

<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>
Copy after login

Suppose you have a form with input fields and you want to validate all fields before submitting the form. In this case, you can use Promise.allSettled() to wait for all validation Promises to complete before deciding whether to submit the form.

Here are the steps to follow:

  • Step 1 - In an HTML document, write a form with input fields. Take its ID as input.

  • Step 2 - Define the validateForm() function that will be called when the form is submitted.

  • Step 3 - Within the validateForm() function, retrieve the value of the input field using the document.getElementById() > method.

  • Step 4- Create an array of validation promises using the validateInput() function and pass the input field values ​​as arguments.

    < /里>
  • Step 5 - Use Promise.allSettled() to wait for all validation Promises to complete.

  • Step 6 - Iterate over the results of Promise.allSettled() and check the status property of each result object. If any Promise is rejected, set the hasErrors flag to true and log an error message.

  • Step 7 - If the hasErrors flag is false, the form is considered valid and can be submitted. If the hasErrors flag is true, the form has errors and should not be submitted.

  • Step 8 - Add the onsubmit attribute to the form element in the HTML form and set it to call the validateForm() function. If the validateForm() function returns false, use a return false statement to prevent the form from being submitted.

Example 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>
Copy after login

Promise.allSettled() can be used in a variety of situations, such as handling network requests and validating user input, and can be used in conjunction with async/await syntax or the then() method to handle the completed value of a Promise.

The above is the detailed content of Explain Promise.allSettled() and async-await in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template