Promises in Javascript : Basic Class You Missed [Part :02 ]

The Deca Dose
3 min readJul 19, 2023

--

Photo by alise storsul on Unsplash

Introduction:
In our previous discussion, we explored the fundamentals of JavaScript Promises and their usage. However, promises offer more than just sequential execution and error handling. In this article, we will dive into advanced promise handling techniques, including `Promise.all`, `Promise.allSettled`, `Promise.race`, and others. Understanding these advanced promise methods will empower you to tackle complex asynchronous scenarios with ease. So, let’s level up our promise game and unlock the full potential of JavaScript!

## Table of Contents:
1. Promise.all: Handling Multiple Promises
2. Promise.allSettled: Handling Multiple Promises with Settled States
3. Promise.race: Resolving with the Fastest Promise
4. Promise.any: Resolving with the First Fulfilled Promise
5. Promise.resolve and Promise.reject
6. Conclusion

## 1. Promise.all: Handling Multiple Promises
The `Promise.all` method allows you to handle multiple promises simultaneously and wait for all of them to resolve or reject. It takes an iterable (e.g., an array) of promises as input and returns a new promise that is fulfilled with an array of resolved values when all promises are successfully resolved. If any promise is rejected, the `Promise.all` promise will be rejected with the reason of the first rejected promise.


const promise1 = fetch(‘https://api.example.com/data1');
const promise2 = fetch(‘https://api.example.com/data2');
const promise3 = fetch(‘https://api.example.com/data3');

Promise.all([promise1, promise2, promise3])
.then(results => {
// Handle the resolved values
console.log(results);
})
.catch(error => {
// Handle the first rejection reason
console.error(error);
});

## 2. Promise.allSettled:

Handling Multiple Promises with Settled States
Unlike `Promise.all`, the `Promise.allSettled` method allows you to handle multiple promises and wait for all of them to settle (resolve or reject), regardless of their outcome. It returns a new promise that is fulfilled with an array of objects, each containing the outcome of the corresponding promise.


const promise1 = fetch(‘https://api.example.com/data1');
const promise2 = fetch(‘https://api.example.com/data2');
const promise3 = fetch(‘https://api.example.com/data3');

Promise.allSettled([promise1, promise2, promise3])
.then(results => {
results.forEach(result => {
if (result.status === ‘fulfilled’) {
console.log(result.value); // Handle resolved value
} else if (result.status === ‘rejected’) {
console.error(result.reason); // Handle rejection reason
}
});
});

## 3. Promise.race:

Resolving with the Fastest Promise
The `Promise.race` method allows you to handle multiple promises but resolves or rejects as soon as the first promise settles (either resolves or rejects). It returns a new promise that settles with the outcome of the fastest promise.


const promise1 = new Promise(resolve => setTimeout(resolve, 2000, ‘Promise 1’));
const promise2 = new Promise(resolve => setTimeout(resolve, 1000, ‘Promise 2’));

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

## 4. Promise.any:

Resolving with the First Fulfilled Promise
The `Promise.any` method allows you to handle multiple promises and resolves as soon as any of the promises fulfill. It returns a new promise that resolves with the value of the first fulfilled promise. If all promises are rejected, it will reject with an `AggregateError` containing the rejection reasons.


const promise1 = new Promise((resolve, reject) => setTimeout(reject, 2000, ‘Promise 1 rejected’));
const promise2 = new Promise(resolve => setTimeout(resolve, 1000, ‘Promise 2’));

Promise.any([promise1, promise2])
.then(result => {
console.log(result); // Output: Promise 2
})
.catch(errors => {
console.error(errors); // Output: AggregateError: All promises were rejected
});
```

## 5. Promise.resolve and Promise.reject
The `Promise.resolve` method returns a resolved promise with the specified value. It can be used to convert a non-promise value into a promise, making it useful for consistency and handling synchronous code.


Promise.resolve(‘Success’)
.then(result => {
console.log(result); // Output: Success
});

Promise.reject(new Error(‘Failed’))
.catch(error => {
console.error(error); // Output: Error: Failed
});
```

## Conclusion
JavaScript promises offer a range of advanced methods to handle complex asynchronous scenarios. By utilizing `Promise.all`, `Promise.allSettled`, `Promise.race`, `Promise.any`, `Promise.resolve`, and `Promise.reject`, you can efficiently manage multiple promises, handle various settling states, and resolve with the fastest or first fulfilled promise. These methods enhance the flexibility and power of promises, empowering you to build robust and efficient asynchronous code.

Remember to leverage these advanced promise handling techniques when faced with complex asynchronous tasks. Happy coding!

Follow this account for upcoming concurrency and scaling with Promises in javascript article with real world working examples

Part 01 : https://medium.com/@vikramgyawali57/demystifying-javascript-promises-unlocking-asynchronous-power-9084818b7d05

*References:
- MDN Web Docs: [Promise.all](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)
- MDN Web Docs: [Promise.allSettled](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled)
- MDN Web Docs: [Promise.race](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race)
- MDN Web Docs: [Promise.any](https://developer.mozilla.org/en-US/docs

--

--

The Deca Dose

Get the top and best suggestions for programming , coding and all the techs