Checkout my Getting Started with React video course on Skillshare. It is 100% free.

Using the Promise all(), race(), allSettled() and any() in Javascript

With the many options for solving multiple multiple concurrent promises things can get a bit confusing. Let's see the options one by one:

  • Promise.all() - resolves only when all of the given promises are resolved. It rejects immediately if one promises fails and returns the first rejection message.

    Promise.all([getUserById(1),getUserById(2), getUserById(3)])
    .then((users) => {
        // will  return all the users
    })
    .catch((error) => {
        // will fail when the first promise fails
    });
  • Promise.allSettled() - it will resolve when all of the given promises have either been fulfilled or rejected.

    Promise.allSettled([getUserById(1), getUserById(2), getUserById(3)])
    .then((results) => {
        // the items in results can be either a user or an error
        // it waits for all the promises to have a result.
    })
  • Promise.race() - will resolve when the first of the given concurrent promises fulfills or rejects.

    Promise.race([getUserById(1), getUserById(2), getUserById(3)])
    .then(([user]) => {
        // will return the first retrevied user
    })
    .catch((error) => {
        // will fail at the first rejected promise
    });
  • Promise.any() - It will resolve as soon as one of the promises is fulfilled, but it won’t reject until it’s done resolving all of the promises. It tries to fulfill at least one promise.

    Promise.any([getUserById(1), getUserById(2), getUserById(3)])
    .then(([user]) => {
        // will return the first retrevied user
    })
    .catch((error) => {
        // will fail only when all the promises have failed
    });
Home Screencasts Best of Newsletter Search X