Home > Article > Web Front-end > Explain Promise.allSettled() and async-await in JavaScript?
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.
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.
The syntax for using Promise.allSettled() is as follows -
Promise.allSettled(iterable);
Iterable is the input provided to promise.allSettled(). Iterable object is an array containing Promises.
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.
async function example() { // asynchronous code goes here }
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 }
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); } } }
The following are two possible use cases for Promise.allSettled() in the real world:
Handling network requests
Handling user input in forms
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>
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.
<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() 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!