DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 17: Promise Executions

⚙️ Parallel Execution

Parallel execution is the process of running multiple asynchronous tasks simultaneously, taking advantage of JavaScript's non-blocking nature to improve performance.

Promise.all([
  Promise.resolve('Success 1'),
  Promise.resolve('Success 2'),
])
.then((result) => {
  console.log(result); // ['Success 1', 'Success 2']
})
Enter fullscreen mode Exit fullscreen mode

The Promise.all() method takes an array of promises as input and returns a new Promise that resolves with an array of results when all the promises in the array have resolved.

🔗 Sequence Execution

We may need to execute multiple asynchronous tasks in a specific order, where the result of one task is dependent on the outcome of the previous one. Promises can be chained together to handle the sequential execution of asynchronous operations.

promise1
.then((result1) => {
  console.log('result from 1 api', result1)
  return promise2;
})
.then((result2) => {
  console.log('result from 2 api', result2);
});
Enter fullscreen mode Exit fullscreen mode

⏱️ First Fulfilled Promise

Sometimes, you might need to respond as soon as one of several Promises is fulfilled.

Promise.race([
  Promise.reject('Error 1'),
  Promise.resolve('Success 1'),
  Promise.reject('Error 2'),
]).then((result) => {
  console.log(result); // won't reach
})
.catch((error) => {
  console.error(error); // Error 1
});
Enter fullscreen mode Exit fullscreen mode

Promise.race() resolves or rejects with the value or reason of the first resolved or rejected Promise.

🏆 First Successful Execution

We may need to wait for the first resolved Promise from an array of Promises.

const promises = [
  Promise.reject('Error 1'),
  Promise.resolve('Success 1'),
  Promise.reject('Error 2'),
];

Promise.any(promises)
.then((result) => {
  console.log(result); // "Success 1"
})
.catch((error) => {
  console.error(error); // AggregateError: All Promises were rejected
});
Enter fullscreen mode Exit fullscreen mode

Promise.any() function that resolves with the result of the first resolved Promise, ignoring any rejections. This way, we ensure that the chain continues with the result of the first resolved Promise.

⚖️ All status

We may need to execute multiple Promises, and you need to know the status (fulfilled or rejected) of each Promise, regardless of its individual outcome.

const promises = [
  Promise.resolve('Success 1'),
  Promise.reject('Error 1'),
  Promise.resolve('Success 2'),
];

Promise.allSettled(promises)
.then((results) => {
  console.log(results);
  /*
  [
    { status: "fulfilled", value: "Success 1" },
    { status: "rejected", reason: "Error 1" },
    { status: "fulfilled", value: "Success 2" },
  ]
  */
});
Enter fullscreen mode Exit fullscreen mode

The Promise.allSettled() method returns a Promise that resolves with an array of objects representing the status of each input Promise.

Top comments (0)