πŸ“• LangChain for JavaScript developers is now out!
Build 5 Next.js apps with ChatGPT integrated features using LangChain.

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

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *