Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
Promise.all versus foreach Promise

I have an Angular calculator application that calculates some results (CalculatorResult) grouped in sheets (like Excel ones). Say we have some six sheets.

I have a method, calculateSheet, that takes some properties, the sheet name, and returns some CalculatorResult[]:

async calculateSheet(
       propertyValues: PropertyValue[],
       sheetTypeName: string): Promise<CalculatorResult[]>

The method calculateSheets that calculates all six sheets, should calculate each of the six sheets, and then aggregate all resulting arrays of the result in a single array (six arrays of CalculatorResult should become one).

So, I tried two methods to aggregate it, below:

// define all promises to be calculated
const promises: (() => Promise<CalculatorResult[]>)[] = [this.selectedSheetTypeName, ...(sheets.value as Sheet[]).map((sheet: Sheet) => sheet.type.name)
  .filter((sheetTypeName: string) => sheetTypeName != this.selectedSheetTypeName)]
  .map((sheetTypeName: string) => this.calculateSheet.bind(this, propertyValues, sheetTypeName));

// now, await all results, and build a common array from 6 arrays(one per sheet) of results
let results: CalculatorResult[] = [];

// WHERE IS THE DIFFERENCE OF

// THIS ONE
const myValues = await Promise.all(promises);
console.log("All 6 sheets promises here bellow:");
console.log(myValues);


// VERSUS THIS ONE
for (const promise of promises) {
  let sheetResults = await promise();
  console.log("Sheet results:")
  console.log(sheetResults)
  results.push(...sheetResults);
  console.log("All results:")
  console.log(results)
}

In the first case (myValues), why do we have six functions as the result, instead of the CalculatorResults array?

Enter image description here

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

TL;DR

As rule of thumb:

  • If you want to execute everything in parallel and have a result as fast as you can, use Promise.all
  • If you want to do the same as above, but have all promise results if one fails, use: allSettled or similar
  • If you want to execute every promise sequentially, use for Promise

First of all, in your example the promises array is actually an array of functions, which you never execute, so that's why Promise.all returns all fns. Fix:

const promises = ….map((sheetTypeName: string) => this.calculateSheet(propertyValues, sheetTypeName));

Promise.all

If all the promises succeed:

  • Will wait until all promises finish, and will return an array of results

If any promise is rejected:

  • No matter when the promise is rejected nor if two or more are rejected, it will return a rejected promise containing the error of the first promise that rejected. It will happen as soon as the first error is thrown.
  • You never know which promise was the one that failed. The error should contain some extra info if you want to know what promise generated it.
  • If two or more promises failed, you will never know. How is the state of the other promises is unknown, since you only get the first error that happened. Other promises might not finish when the promise is rejected.
  • If you want to wait for every promise is resolved/rejected, you may use allSettled or something similar.

for promises

The main difference is that will execute each function sequentially. It will wait to execute & finish the first one, to then execute the second one, and so on.

Also, you control the flow, so if the first one fails, you can choose to continue or not, or what to do.

BTW, I would never use bind to implement this, would execute every method/function directly in the for

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!