Sling Academy
Home/JavaScript/JavaScript Promise.allSettled() method (with examples)

JavaScript Promise.allSettled() method (with examples)

Last updated: February 14, 2024

Overview

Understanding the asynchronous behavior of JavaScript is crucial for modern web development. One of the key aspects of managing asynchronous operations in JavaScript is the use of Promises. Promises provide a way to handle the eventual success or failure of an asynchronous operation. With the evolution of JavaScript, different methods have been introduced to handle multiple promises efficiently. Among them, Promise.allSettled() is a method that promises to bring robustness to handling numerous asynchronous operations. In this guide, we will dive deep into how Promise.allSettled() works with practical examples.

What is Promise.allSettled()?

Promise.allSettled() is a JavaScript method that takes an array of Promises and returns a new Promise that resolves after all the given promises have either fulfilled or rejected. The resolution of Promise.allSettled() is an array of objects that each describes the outcome of each promise, making it possible to handle both successful and failed promises efficiently.

Why Use Promise.allSettled()?

Previously, developers heavily relied on Promise.all() to handle multiple promises. However, Promise.all() has a significant limitation: it fails fast, meaning if any of the promises in the array rejects, the whole operation is considered a failure. This is where Promise.allSettled() brings its value, allowing developers to wait for all promises to settle, regardless of the outcome.

Basic Syntax

Promise.allSettled(promisesArray).then(results => {
    results.forEach((result) => {
        if (result.status === 'fulfilled') {
            console.log('Success:', result.value);
        } else {
            console.log('Failure:', result.reason);
        }
    });
});

Examples

Let’s look at some practical examples to understand how Promise.allSettled() can be effectively used.

Example 1: Basic Use Case

const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));

Promise.allSettled([promise1, promise2])
.then((results) => {
    results.forEach((result) => {
        console.log(result);
    });
});

In this example, promise1 is a promise that is immediately resolved with the value 3, and promise2 is a promise that is rejected after 100 milliseconds with the reason ‘foo’. Promise.allSettled() waits for both promises to settle and then logs each result.

Example 2: Handling Multiple Asynchronous Operations

const userPromise = fetchUserById(1); // Assume this returns a promise
const postsPromise = fetchPostsForUser(1); // Assume another promise

Promise.allSettled([userPromise, postsPromise])
.then((results) => {
    const userResult = results[0];
    const postsResult = results[1];

    if (userResult.status === 'fulfilled') {
        console.log('User fetched successfully:', userResult.value);
    } else {
        console.log('User fetch failed:', userResult.reason);
    }

    if (postsResult.status === 'fulfilled') {
        console.log('Posts fetched successfully:', postsResult.value);
    } else {
        console.log('Posts fetch failed:', postsResult.reason);
    }
});

This example highlights how Promise.allSettled() can be used to handle multiple asynchronous operations such as fetching a user and their posts from a database or API. Regardless of whether one operation fails, the other results are still processed.

Handling Complex Scenarios

In more complex applications, you might encounter scenarios where you have to manage multiple groups of promises, each with different importance levels. Promise.allSettled() can be particularly useful in these situations by allowing you to group promises and handle their results collectively, providing greater flexibility in how you manage asynchronous operations.

Conclusion

Promise.allSettled() is a powerful tool in the JavaScript developer’s arsenal, providing a new level of robustness in handling multiple asynchronous operations. By enabling developers to wait for all promises to settle regardless of their outcome, Promise.allSettled() makes it easier to manage complex operations and handle cases where certain tasks may fail without impacting the overall operation. As you continue to build and work with JavaScript applications, consider how Promise.allSettled() might improve your asynchronous operations handling.

Next Article: JavaScript String replaceAll() method (with examples)

Previous Article: JavaScript console.table() method (with examples)

Series: JavaScript Basics

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration