Methods of Promises in JavaScript
In this short article, weโll show you the list of the methods of Promises in JavaScript.
Checkout more articles on JavaScript
- 7 JavaScript One-Liners that you should know
- Add days to a date in JavaScript
- Encode and decode strings with base64 in JavaScript
- Remove the leading zero from a number in JavaScript
- How to merge arrays in JavaScript
Methods of Promises in JavaScript
1. Promise.all()
The `Promise.all()` method takes an array (an iterable) of promises and returns a single Promise that resolves to an array of the results.
const promise1 = Promise.resolve(21);
const promise2 = 55;
const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 100, "Clue Mediator"));
Promise.all([promise1, promise2, promise3]).then(values => {
console.log(values); // Output: [21, 55, "Clue Mediator"]
});
2. Promise.allSettled()
The `Promise.allSettled()` method returns a promise that resolves after all of the given promises have either been fulfilled or rejected, with an array of objects that each describes the outcome of each promise.
const promise1 = Promise.resolve(21);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, "Test String"));
const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 100, "Clue Mediator"));
Promise.allSettled([promise1, promise2, promise3]).then(results => {
results.map(x => console.log(x.status));
// Output:
// "fulfilled"
// "rejected"
// "fulfilled"
});
3. Promise.any()
`Promise.any()` takes an iterable of Promise objects and, as soon as one of the promises in the iterable fulfills, returns a single promise's value.
If no promises in the iterable fulfill, then the returned promise is rejected.
const promise1 = Promise.reject(10);
const promise2 = new Promise((resolve, reject) => setTimeout(resolve, 100, "quick result"));
const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 500, "slow result"));
Promise.any([promise1, promise2, promise3]).then(value => {
console.log(value); // Output: "quick result"
});
4. Promise.race()
The `Promise.race()` method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise.
const promise1 = new Promise((resolve, reject) => setTimeout(resolve, 500, "slow result"));
const promise2 = new Promise((resolve, reject) => setTimeout(resolve, 100, "quick result"));
Promise.race([promise1, promise2]).then(value => {
console.log(value); // Output: quick result
// Both resolve, but promise2 is faster
});
Here you will also find more information about the Promise.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! ๐