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.