Code Premix

Method of promises in JavaScript with example

📅July 10, 2022|🗁JavaScript

In this short article, we’ll show you the list of the methods of Promises in JavaScript with example.

  1. Promise.all()
  2. Promise.allSettled()
  3. Promise.any()
  4. Promise.race()

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, "Code Premix"));

Promise.all([promise1, promise2, promise3]).then(values => {
  console.log(values); // Output: [21, 55, "Code Premix"]
});

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, "Code Premix"));

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..!!