Sanjoy Saha

Dec 13, 2024 • 2 min read • 

Power of Promise APIs in JavaScript

Here is a beginner-friendly blog on Promise APIs in JavaScript

Power of Promise APIs in JavaScript

Introduction

Asynchronous programming is used in modern JavaScript development. Promises provide a powerful way to handle asynchronous tasks and JavaScript comes with several built in Promise APIs to make working with them more easier.

In this blog I have mentioned about Promise APIs like Promise.all, Promise.race, Promise.allSettled and Promise.any their use cases and examples to help you understand how to use them.


What is a Promise?

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It can be in one of three states:

  1. Pending: The initial state, neither fulfilled nor rejected.

  2. Fulfilled: The operation was successful.

  3. Rejected: The operation failed.


Types of promises

1. Promise.all

It runs multiple promises in parallel and waits until all of them are resolved or one is rejected.

Syntax:

Promise.all([promise1, promise2, promise3])
  .then(results => { /* Handle results */ })
  .catch(error => { /* Handle error */ });

Use Case:

You want to fetch data from multiple APIs and wait for all the data to load.

Example:

const fetchData1 = fetch('https://api.example.com/data1');
const fetchData2 = fetch('https://api.example.com/data2');

Promise.all([fetchData1, fetchData2])
  .then(responses => Promise.all(responses.map(res => res.json())))
  .then(data => console.log('All data:', data))
  .catch(error => console.error('Error:', error));

If any promise fails, Promise.all rejects immediately.


2. Promise.race

Promise.race returns the result of the first promise that resolves or rejects.

Syntax:

Promise.race([promise1, promise2, promise3])
  .then(result => { /* Handle first result */ })
  .catch(error => { /* Handle first error */ });

Use Case:

You need the fastest response among multiple sources.

Example:

const fetchFast = fetch('https://api.fast.com/data');
const fetchSlow = fetch('https://api.slow.com/data');

Promise.race([fetchFast, fetchSlow])
  .then(result => console.log('First response:', result))
  .catch(error => console.error('Error:', error));

3. Promise.allSettled

Promise.allSettled waits for all promises to settle (either fulfilled or rejected) and returns an array of their outcomes.

Syntax:

Promise.allSettled([promise1, promise2, promise3])
  .then(results => { /* Handle all results */ });

Use Case:

You want the results of all promises, regardless of their success or failure.

Example:

const promise1 = Promise.resolve('Success');
const promise2 = Promise.reject('Failed');

Promise.allSettled([promise1, promise2])
  .then(results => console.log('Results:', results));

Output:

[
  { status: 'fulfilled', value: 'Success' },
  { status: 'rejected', reason: 'Failed' }
]

4. Promise.any

Promise.any waits for the first promise to resolve. If all promises are rejected, it throws an error.

Syntax:

Promise.any([promise1, promise2, promise3])
  .then(result => { /* Handle first resolved result */ })
  .catch(error => { /* Handle all failures */ });

Use Case:

You want the first successful result from multiple attempts.

Example:

const promise1 = Promise.reject('Error 1');
const promise2 = Promise.resolve('First Success');
const promise3 = Promise.resolve('Another Success');

Promise.any([promise1, promise2, promise3])
  .then(result => console.log('First success:', result))
  .catch(error => console.error('All failed:', error));

Best Practices and Tips

  1. Use Promise.all when all promises are interdependent and you need every result.

  2. Use Promise.race for scenarios requiring the fastest response.

  3. Use Promise.allSettled for tasks where you need all results, regardless of success or failure.

  4. Use Promise.any for fault-tolerant systems where any successful result is sufficient.

  5. Handle errors gracefully using .catch() or try...catch when using async/await.


Conclusion

The Promise APIs are really useful for managing asynchronous tasks in JavaScript. By understanding their differences and use cases, you can write better and more efficient code according to project’s needs.

Join Sanjoy on Peerlist!

Join amazing folks like Sanjoy and thousands of other people in tech.

Create Profile

Join with Sanjoy’s personal invite link.

0

1

0