Understanding Promises in JavaScript

kawanedres

Kawan Idrees

Posted on November 28, 2023

Understanding Promises in JavaScript

Promises are a powerful feature in JavaScript for handling asynchronous operations. They provide a way to deal with the results or errors of asynchronous operations in a more organized and readable manner. In this blog post, we'll explore three commonly used Promise methods:
1-Promise.all
2-Promise.allSettled
3-Promise.race.

Promise.all
Promise.all is a method that takes an iterable of promises as an input and returns a single promise. This returned promise is fulfilled with an array of the fulfilled values of the input promises, in the same order as the input promises. If any of the input promises is rejected, the entire Promise.all is rejected with the reason of the first promise that was rejected.

Here's a simple example:

const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = Promise.reject(new Error('Failed'));

Promise.all([promise1, promise2, promise3])
  .then(values => console.log(values))
  .catch(error => console.error(error.message));
// Output: Error: Failed


Enter fullscreen mode Exit fullscreen mode

In this example, since promise3 is rejected, the entire Promise.all is rejected, and the catch block is triggered.

Promise.allSettled
Promise.allSettled is similar to Promise.all but with a key difference. It returns a promise that is fulfilled with an array of result objects for each input promise. Each result object has a status property that can be either "fulfilled" or "rejected". This way, even if some promises fail, the others are still processed, and you can handle each promise's success or failure independently.

Here's an example:

const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = Promise.reject(new Error('Failed'));

Promise.allSettled([promise1, promise2, promise3])
  .then(results => results.forEach(result => {
    if (result.status === 'fulfilled') {
      console.log(result.value);
    } else {
      console.error(result.reason.message);
    }
  }));
// Output: 1, 2, Error: Failed

Enter fullscreen mode Exit fullscreen mode

In this example, even though promise3 is rejected, the Promise.allSettled continues to process the other promises, and you can handle their success or failure individually.

Promise.race
Promise.race is another method that takes an iterable of promises and returns a promise that is settled with the value or reason of the first promise that settles (fulfills or rejects). It can be useful when you are interested in the result of the first promise to be resolved.

Here's an example:

const promise1 = new Promise(resolve => setTimeout(() => resolve('Promise 1'), 1000));
const promise2 = new Promise(resolve => setTimeout(() => resolve('Promise 2'), 500));

Promise.race([promise1, promise2])
  .then(value => console.log(value))
  .catch(error => console.error(error.message));
// Output: Promise 2

Enter fullscreen mode Exit fullscreen mode

In this example, since promise2 is resolved faster than promise1, the entire Promise.race is resolved with the value of promise2.

Conclusion
In summary, Promise.all is used when you want all promises to be fulfilled, but if any of them fail, the entire operation fails. Promise.allSettled is used when you want to handle the fulfillment or rejection of each promise independently, ensuring that one failing promise does not prevent others from being processed. Promise.race is used when you are interested in the result of the first settled promise.

Each of these methods has its use cases, and understanding their differences allows you to choose the most appropriate one for your specific scenario. Whether you need all promises to succeed, want to handle success and failure independently, or are interested in the first settled promise, JavaScript's Promise methods provide flexible tools for handling asynchronous operations.

💖 💪 🙅 🚩
kawanedres
Kawan Idrees

Posted on November 28, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related