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


Promise.allSettled() is a method that takes an iterable of promises as an argument and returns a promise that is fulfilled when all of the promises in the iterable have been settled, meaning that they have either been fulfilled or rejected.

When the returned promise is fulfilled, it is resolved with an array of objects containing information about the fulfilled or rejected promises. Each object has a status property, either fulfilled or rejected, and a value or reason property, respectively.

For example, if you have an array of promises that represent network requests and want to know each request's status (whether it was successful or not), you can use Promise.allSettled() to wait for all of the requests to complete before handling the results.

Promise.allSettled

Using Promise.allSettled() can be useful when you want to handle the results of multiple promises, regardless of whether they are fulfilled or rejected. It is different from Promise.all(), which will only resolve if all of the promises are fulfilled and will reject if any of the promises are rejected.

Syntax

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

Promise.allSettled(iterable);

Iterable is an input given to promise.allSettled(). iterable object is an array containing promises.

Async-await

The async and await keywords in JavaScript that are used to work with asynchronous code. The async is used before a function definition to denote that the function is asynchronous and will return a promise.

Syntax

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

The await is used inside an async function to pause the execution until a specified promise is fulfilled.

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

Promise.allSetlled with 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 similar to synchronous code without the need for callbacks or the then() method.

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

Here 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);
      }
   }
}

Here 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 of the requests, regardless of whether they are successful or not, you can use Promise.allSettled() to wait for all of the 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 field, and you want to validate all of the fields before submitting the form. In that 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 be followed:

  • Step 1 − In an HTML document, write a form with an input field. Give it id as input.

  • Step 2 − Define the validateForm() function, which will be called when the form is submitted.

  • Step 3 − Inside the validateForm() function, retrieve the value of the input fiel using the document.getElementById() method.

  • Step 4 − Create an array of validation promises using the validateInput() function, passing the input field value as an argument.

  • 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 promises have been 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 an onsubmit attribute to the form element in the HTML form and set it to call the validateForm() function. Use the return false statement to prevent the form from being submitted if the validateForm() function returns false.

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>

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

Updated on: 29-Dec-2022

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements