Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 3017

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T10:49:08+00:00 2024-11-26T10:49:08+00:00

The difference between Promise.all() vs Promise.allSettled() vs Promise.any() vs Promise.race() in 30 seconds

  • 61k

If you're writing code in JavaScript or TypeScript (or CoffeeScript for whatever reason!) you'll come across Promises. One of the best features they provide is concurrency, which is usually achieved with Promise.all(). That being said, I'd like to quickly explore the differences between the available methods: all(), allSettled(), any() and race() (this last one I hadn't even heard of until researching for this article!).

At a glance

All of them start the Promises concurrently (not necessarily in parallel!). They all ignore non-promises.

  • all(): Resolves only if all promises resolve. Early reject if any one promise rejects. Returns an array of the settled values in the order they were inserted, not settled. Promise.all() resolves synchronously if and only if the iterable passed is []. Even if you pass [1, 'abc', {}], it will resolve asynchronously.
  • allSettled(): Resolves only if all promises resolve. Reject if any one promise rejects (just like all() so far) BUT WAITS FOR ALL OTHERS TO FINISH. Returns an array of the settled status and values in the order they were inserted, not settled.
  • any(): Resolves if any promise resolves. Rejects only if all the promises reject (opposite to all()). Returns the first resolved value.
  • race(): Rejects or resolves according to whatever the first settled promise does. Returns the first resolved value.

Don't forget to check out all my other content for more guides like this one!


Here is some code you can test yourself to check the results. Feel free to test it out and comment any findings you may have!

Here is the GitHub repo too. Give it a star ⭐ while you're at it!

/* All of them start the Promises concurrently (not in parallel necessarily!). They all ignore non-promises.  - all(): Resolves only if all promises resolve. Early reject if any one promise rejects.     Returns an array of the settled values in the order they were inserted, not settled.     Promise.all() resolves synchronously if and only if the iterable passed is []. Even if you pass [1,'abc',{}], it will resolve asynchronously.  - allSettled(): Resolves only if all promises resolve. Reject if any one promise rejects BUT WAITS FOR ALL OTHERS TO FINISH.     Returns an array of the settled stati and values in the order they were inserted, not settled.  - any(): Resolves if any promise resolves. Rejects only if all the promises reject (opposite to all()).     Returns the first resolved value.  - race(): Rejects or resolves according to whatever the first settled promise does.     Returns the first settled value. */ let immediateResolve: Promise<number>,   nonPromise: number,   timeoutPromise: Promise<string>;  function setPromises() {   immediateResolve = Promise.resolve(3);   nonPromise = 42;   timeoutPromise = new Promise((resolve, _) => {     setTimeout(resolve, 1000, "Resolved after timeout");   }); }  async function tryPromiseAll() {   setPromises();   const result = await Promise.all([     immediateResolve,     nonPromise,     timeoutPromise,   ]);   console.log("Promise.all 1: ", result); // Expected output (after at least 1000ms): Array [3, 42, "foo"]    setPromises();   try {     const resultWithRejection = await Promise.all([       immediateResolve,       nonPromise,       timeoutPromise,       Promise.reject("Immediate reject"),     ]);     console.log("Promise.all 2: ", resultWithRejection); // Never reached, rejection causes interruption   } catch (error) {     console.error("Error:", error);   }    setPromises();   try {     const resultWithCaughtRejection = await Promise.all([       immediateResolve,       nonPromise,       timeoutPromise,       Promise.reject("Immediate reject").catch(() => {}),     ]);     console.log("Promise.all 3: ", resultWithCaughtRejection); // Expected: [ 3, 42, 'Resolved after timeout', undefined ]. Rejection is never bubbled up   } catch (error) {     console.error("Error:", error);   } }  async function tryPromiseAllSettled() {   setPromises();   const result = await Promise.allSettled([     immediateResolve,     nonPromise,     timeoutPromise,   ]);   console.log("Promise.allSettled 1: ", result);   // Expected output: [{ status: 'fulfilled', value: 3 }, { status: 'fulfilled', value: 42 }, { status: 'fulfilled', value: 'Resolved after timeout' }]    setPromises();    try {     const resultWithRejection = await Promise.allSettled([       immediateResolve,       nonPromise,       timeoutPromise,       Promise.reject("Immediate reject"),     ]);     console.log("Promise.allSettled 2: ", resultWithRejection);     // Expected output: [{ status: 'fulfilled', value: 3 }, { status: 'fulfilled', value: 42 }, { status: 'fulfilled', value: 'Resolved after timeout' }, { status: 'rejected', reason: 'Immediate reject' }]   } catch (error) {     console.error("Error:", error);   } }  async function tryPromiseAny() {   setPromises();   const result = await Promise.any([     immediateResolve,     nonPromise,     timeoutPromise,   ]);   console.log("Promise.any 1: ", result); // Expected output: 3, not 2, as it doesn't come from a promise    setPromises();    try {     const resultWithRejection = await Promise.any([       immediateResolve,       nonPromise,       timeoutPromise,       Promise.reject("Immediate reject"),     ]);     console.log("Promise.any 2: ", resultWithRejection); // Always reached unless they all rejected   } catch (error) {     console.error("Error:", error);   } }  async function tryPromiseRace() {   setPromises();   const result = await Promise.any([     immediateResolve,     nonPromise,     timeoutPromise,   ]);   console.log("Promise.race 1: ", result); // Expected output: 3    setPromises();    try {     const resultWithRejection = await Promise.any([       immediateResolve,       nonPromise,       timeoutPromise,       Promise.reject("Immediate reject"),     ]);     console.log("Promise.race 2: ", resultWithRejection); // Never reached   } catch (error) {     console.error("Error:", error);   } }  export default async function main(): Promise<void> {   console.log("Starting test:
");   console.time("Promise.all");   await tryPromiseAll();   console.timeEnd("Promise.all");   console.log("");    console.time("Promise.allSettled");   await tryPromiseAllSettled();   console.timeEnd("Promise.allSettled");   console.log("");    console.time("Promise.any");   await tryPromiseAny();   console.timeEnd("Promise.any");   console.log("");    console.time("Promise.race");   await tryPromiseRace();   console.timeEnd("Promise.race"); }  main()   .then(() => {     process.exit(0);   })   .catch((error) => {     console.error(error);     process.exit(1);   }); 
Enter fullscreen mode Exit fullscreen mode


Sources: all(), allSettled(), any(), race()

javascriptprogrammingtodayilearnedwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.