Blog/NotesConcept

Notes to Master Promises Methods - all(), allSettled(), race(), any()

Understanding promise's methods is important to call APIs in parallel and it's an important concept to know for any machine coding interview.

Intermediate

Anuj Sharma

Last Updated Aug 31, 2024


Understanding promises static methods is very important for handling promises in different scenarios, especially in API calls. This concept is very important to understand for javascript and machine coding interview rounds

Promise Static Methods

Quick Summary

Promise.all()

Run promises in parallel, and return "all fulfilled response" If anyone failed then the whole result failed with an error.

Promise.allSetteled()

Run promises in parallel, return "all settled response" (either fulfilled or rejected)

Promise.race()

Run promises in parallel, return "first settled response" (either fulfilled or rejected )

Promise.any()

Run promises in parallel, return "first fulfilled response", if all rejected return AggregateError object with all the rejected errors as part of the errors object

Let's Understand Promise Methods in Depth

Promise.all()

Promise.all([promises]) used to call promises in parallel.

  • It returns an array of results in case all the promises got `resolved`, in case of any failure it returns the error immediately and other promises are ignored.
  • Returns a promise Asynchronously, when the iterator contains one or more resolved promises
    let p = Promise.all([10, Promise.resolve(30), 40]);
    p.then((values) => console.log(values)) // log: [10, 30, 40]
  • If an Empty Iterable is passed - then the promise returned by this method is fulfilled synchronously. The resolved value is an empty array.
    // Synchronously return resolved promise
    let p = Promise.all([])
    p.then((value) => console.log(value)) // log: []
    
    // Asynchronously return resolved promise in case all non-promise iterators
    let p = Promise.all([10, 20, 30])
    p.then((value) => console.log(value)) // log: [10, 20, 30]
  • If a "Nonempty Iterable" is passed, and all of the promises are fulfilled or are not promises, then the promise returned by this method is fulfilled asynchronously.
    let p = Promise.all([ Promise.resolve(44), 55, 66])
    p.then((value) => console.log(value)) // log: [44, 55, 66]
  • If Iterable contains a rejected promise, then returns a promise which failed at the first rejection and returns an error with the rejection callback.
    // Return first rejected promise if there is any rejection
    let p = Promise.all([
    	Promise.resolve(10),
    	Promise.reject('first reject'),
    	Promise.reject('second reject')
    ])
    
    p.then(null, (err) => {
    	console.log(err) // Log: 'first reject'
    })
    // or
    p.catch((err) => {
    	console.log(err) // Log: 'first reject'
    })

Promise.allSettled(iterable)

Promise.allSettled just waits for all promises to settle, regardless of the result. The resulting array has

  • {status: "fulfilled", value: result} for successful responses,
  • {status: "rejected", reason: error} for errors.
let urls = [
  'https://api.github.com/users/iliakan',
  'https://api.github.com/users/remy',
  'https://no-such-url'
];

Promise.allSettled(urls.map( async url => await fetch(url)))
  .then(results => {
    results.forEach((result, num) => {
			// Fulfilled results
      if (result.status == "fulfilled") {
        alert(`${urls[num]}: ${result.value.status}`);
      }
			// Rejected results
      if (result.status == "rejected") {
        alert(`${urls[num]}: ${result.reason}`);
      }
    });
  });

Promise.race(iterable)

Similar to "Promise.all" but waits only for the first settled promise and gets its result (or error).

// First fulfilled
Promise.race([
  new Promise((resolve, reject) => setTimeout(() => resolve(1), 1000)),
  new Promise((resolve, reject) => setTimeout(() => reject(new Error("Whoops!")),2000)),
  new Promise((resolve, reject) => setTimeout(() => resolve(3), 3000))
]).then(alert); // 1

// First rejected
Promise.race([
  new Promise((resolve, reject) => setTimeout(() => resolve(1), 5000)),
  new Promise((resolve, reject) => setTimeout(() => reject(new Error("Whoops!")), 2000)),
  new Promise((resolve, reject) => setTimeout(() => resolve(3), 3000))
]).then(alert)
.catch(alert) // Whoops!

Promise.any(iterable)

Similar to Promise.race, but waits only for the first fulfilled promise and gets its result.

If all of the given promises are rejected, then the returned promise is rejected with AggregateError – a special error object that stores all promise errors in its errors property.

Promise.any([
  new Promise((resolve, reject) => setTimeout(() => reject(new Error("Whoops!")),1000)),
  new Promise((resolve, reject) => setTimeout(() => resolve(1), 2000)), // 1st fulfilled
  new Promise((resolve, reject) => setTimeout(() => resolve(3), 3000))
]).then(alert); // 1

All rejected promise → AggregateError

Promise.any([
  new Promise((resolve, reject) => setTimeout(() => reject(new Error("Ouch!")), 1000)),
  new Promise((resolve, reject) => setTimeout(() => reject(new Error("Error!")), 2000))
]).catch(error => {
  console.log(error.constructor.name); // AggregateError
  console.log(error.errors[0]); // Error: Ouch!
  console.log(error.errors[1]); // Error: Error!
});

Flaunt You Expertise/Knowledge & Help your Peers

Sharing your knowledge will strengthen your expertise on topic. Consider writing a quick Blog/Notes to help frontend folks to ace Frontend Interviews.

Other Related Blogs

Apply Polyfill in JavaScript: Step by Step Explanation (For Interview)

Anuj Sharma

Last Updated Nov 29, 2024

Understand how the apply method works in JavaScript and cover step by step-by-step explanation of the apply method polyfill in JavaScript to understand its internal implementation.

Explained Web Authorization Techniques - Session & JWT

Anuj Sharma

Last Updated Nov 24, 2024

Understand important web authorization techniques to enhance role-based authentication for any web application with popular techniques like Session & JSON Web Token (JWT)

5 Ultimate Rules to master this keyword in JavaScript

Anuj Sharma

Last Updated Nov 22, 2024

Easy to understand 5 rules, that cover the behaviour of the "this" keyword in different contexts and helps you to master this keyword for any javascript interview.

What is CORS ? Cross-Origin Resource Sharing Explained [For Interviews]

Anuj Sharma

Last Updated Nov 16, 2024

A brief explanation of Cross-Origin Resource Sharing (CORS) concept to enable client application accessing resources from cross domain and HTTP headers involved to enable resource access.

Ultimate guide to REST API calls using Fetch: Machine Coding Essential

Vivek Chavan

Last Updated Sep 15, 2024

You will get a clear understanding about working with any rest api and common concepts asked during interviews

Call Polyfill in JavaScript: Step by Step Explanation (For Interviews)

Anuj Sharma

Last Updated Nov 30, 2024

A brief description of the "call" method in JavaScript and a step-by-step explanation of how to create call Polyfill in JavaScript by understanding its internal implementation.

FrontendGeek
FrontendGeek

© 2024 FrontendGeek. All rights reserved