4

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

 3 years ago
source link: http://www.js-craft.io/blog/using-the-promise-all-race-allsettled-and-any-in-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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
    });

I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.

Newsletter subscribe:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK