Home > Mobile >  Differences between two styles of async/await in JavaScript from a performance perspective
Differences between two styles of async/await in JavaScript from a performance perspective

Time:06-30

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.

CodePudding user response:

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`);
  });

})();

  • Related