DEV Community

Cover image for 🤫 Secret JavaScript Methods They Don't Want You To See (part 3): Promise.allSettled()
Dominic Magnifico
Dominic Magnifico

Posted on

🤫 Secret JavaScript Methods They Don't Want You To See (part 3): Promise.allSettled()

Promises are a feature in JavaScript that has always melted my small frontend focused brain. But as a frontend developer’s job bleeds more and more into the backend, it’s important we understand their mysteries.allSettled offers an alternative to the more common resolve and reject. Let’s see how we can use this method to help us when working with multiple promises.

The challenge 🤬

Picture this common scenario: you're tasked with a feature that includes fetching data from different APIs, handling user authentication, and managing various database queries. Each operation is encapsulated within a promise, leading to a spaghetti nightmare of asynchronous tasks.

Traditionally, you might have used Promise.all() to manage these promises, which fulfills when all of the input promises themselves fulfill, or rejects when any of the input's promises rejects, with this first rejection reason. However, what if you want to ensure that every promise resolves, regardless of individual successes or failures?

The magic 🧙‍♂️

Promise.allSettled(), a JavaScript method that operates on an array of promises, provides a comprehensive and reliable outcome. Unlike its counterparts, this method doesn't bail out at the first rejection; instead, it patiently awaits the resolution of all promises, regardless of their individual outcomes.

Check out a real world scenario with me.

const promises = [
  fetch('https://swapi.dev/api/planets/1'),
  fetch('https://swapi.dev/api/people/1'),
  fetch('https://swapi.dev/api/films/1'),
];

Promise.allSettled(promises)
  .then(results => {
    results.forEach(result => {
      if (result.status === 'fulfilled') {
        console.log('Data:', result.value);
      } else {
        console.error('Error:', result.reason);
      }
    });
  })
  .catch(error => console.error('Failed to fetch all data:', error));

Enter fullscreen mode Exit fullscreen mode

In this scenario, Promise.allSettled() gracefully handles multiple fetch requests, logging both the retrieved data and any encountered errors. It ensures that even if some requests fail, the code doesn't break, and you receive feedback on each promise's outcome.

The versatility of Promise.allSettled() extends beyond simple data fetching. Imagine a scenario in an e-commerce application where you need to process multiple transactions concurrently. Utilizing this method allows you to ensure that each transaction is handled appropriately, whether completed successfully or encountering issues. This not only provides valuable insights into transaction statuses but also maintains the application's stability and user experience.

An Unbreakable Promise 🪨

As someone who knows less about JavaScript Promises than I should, it’s important for me to explore and understand these methods. Promise.allSettled() is unique in its ability to handle multiple promises while acknowledging both success and failure. This ensures that no promise is left unattended, and helps me to not pull out what little hair I have dealing with a chain of Promises that may fail and break my entire feature.

Top comments (0)