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

257
Views
Differences between two styles of async/await in JavaScript from a performance perspective

I have come across two common styles of async/await JavaScript code:

 for await (const a of [x1, x2, x3, x4]) 
 { 
   //do stufF
 }

and

 [x1, x2, x3, x4].forEach(async (a) { 
  //do stuff
 }

Are there any performance (or other) advantages to either of these?

edit: Assume that each instance of x is a promise.

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

0

The for loop will not continue to the next entry in the loop until the promise has settled.

The forEach loop will trigger the async function you pass to it for each promise immediately and, assuming you await the promise inside that function, it will go to sleep until the promise resolves.

Given that your variables contain promises, whatever work they are doing is already being done in parallel, so the only decision factor here is if you want to continue their processing in order or as soon as possible.

(async function() {

  const x1 = new Promise(r => setTimeout(() => {
    console.log('Resolve x1');
    r("x1")
  }, 3500));
  const x2 = new Promise(r => setTimeout(() => {
    console.log('Resolve x2');
    r("x2")
  }, 4000));
  const x3 = new Promise(r => setTimeout(() => {
    console.log('Resolve x3');
    r("x3")
  }, 3000));
  const x4 = new Promise(r => setTimeout(() => {
    console.log('Resolve x4');
    r("x4")
  }, 2000));

  for await (const a of [x1, x2, x3, x4]) {
    console.log(`${a} available inside loop`);
  }

})();

(async function() {

  const x1 = new Promise(r => setTimeout(() => {
    console.log('Resolve x1');
    r("x1")
  }, 3500));
  const x2 = new Promise(r => setTimeout(() => {
    console.log('Resolve x2');
    r("x2")
  }, 4000));
  const x3 = new Promise(r => setTimeout(() => {
    console.log('Resolve x3');
    r("x3")
  }, 3000));
  const x4 = new Promise(r => setTimeout(() => {
    console.log('Resolve x4');
    r("x4")
  }, 2000));

  [x1, x2, x3, x4].forEach(async function (a) {
    const value = await a;
    console.log(`${value} available inside loop`);
  });

})();

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!