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

169
Views
Node JS: execution-time-wise, is generating array of promises and then using Promise.all better than looping and instantly awaiting every task?

Suppose we have an array of objects that we have to upload to a cloud service, the service will do something with each object and the return a result. The service's client library has single function that uploads the object and waits for response. Which code will run faster:

async function extractDataInstantAwait(documents) {
  const results = [];
  for (const doc of documents) {
    results.push(await client.extractData(doc));
  }
  return results;
}
async function extractDataPromiseAll(documents) {
  const results = [];
  for (const doc of documents) {
    results.push(client.extractData(doc));
  }
  return Promise.all(results);
}

As far as I know, Nodejs does not run async code in multiple threads, so one may think that there is no difference between those. But, since every call to client.extractData may have to wait for response, the event loop of Nodejs should switch to next promise, do things there (upload another doc), and repeat. Perhaps, if service is slow at parsing each object, but we know it creates new threads for each operation, we can achieve some sort of concurent speed up?

Is my logic correct?

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

0

Promise.all is faster, because Promise.all lets all the promises run in parallel, so your execution time will be the execution time of the longest promise (or close to it).

If you do it in a loop, the promises are executed one after the other, so your execution time will be the sum of all of the promises' execution times.

If you have to await three promises A, B and C which take respectively 200, 300 and 500 ms. With Promise.all they will run concurrently and you will have to wait for C for 500ms (A and B will have completed before that). With a loop you will have to wait 200ms for A, then wait 300ms for B, then wait 500ms for C, so you'll wait 1000ms in total.

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!