Javascript Promise - all/race (Examples)

Tech:
Javascript
Since:
1 year ago
Views:
4

In Javascript promises are used to handle asynchronous operations. It is either resolved or rejected based on the result of the asynchronous operation.

all / race

In Promise 'all' resolve multiple promises and returns an array if all the promises resolved. In 'all', if any one promise is rejected, it returns reject only for that one. The 'race' returns the promise which is first resolved.

var done1 = true;
var done2 = true;

const isJobDone1 = new Promise((resolve, reject) => {
  if (done1) {
    resolve("Job  1 done");
  } else {
    reject("Still working 1");
  }
});

const isJobDone2 = new Promise((resolve, reject) => {
  setTimeout(function() {
    if (done2) {
      resolve("Job  2 done");
    } else {
      reject("Still working 2");
    }
  }, 2000);
});

// All
Promise.all([isJobDone1, isJobDone2])
  .then(val => {
    console.log(val);
  })
  .catch(val => {
    console.log(val);
  });

// Race
Promise.race([isJobDone1, isJobDone2])
  .then(val => {
    console.log(val);
  })
  .catch(val => {
    console.log(val);
  });