0

using for-loop

    let arr=[]
    for (let mkt of markets) {
      const resA = await someAsyncFuncA(context, mkt[0].serumMarket);
      const resB = await someAsyncFuncB(resA);
      console.log(resB) 
      arr.push(resB)
    }
    console.log(arr) // it will log after the for-loop complete 

But when I am using map().

    let arr = [];
     markets.map(async (mkt) => {
      const resA = await someAsyncFuncA(context, mkt[0].serumMarket);
      const resB = await someAsyncFuncB(resA);
      console.log(resB) // it will log after console.log(arr) below
      arr.push(resB)
    });
    console.log(arr) // it will log first: []

I want to understand more for these 2 kinds of loop, such as the performance.
It seems map() always executes faster than for-loop, should I always use map()?
When should I use for-loop?

CCCC
  • 5,665
  • 4
  • 41
  • 88
  • `map` doesn't waits for promises to settle, that is why the last `console.log` statement executes early. – Yousaf Jan 26 '22 at 06:21
  • It doesn’t “execute faster”. This is unrelated to performance. `await` stops execution of the current function until a Promise is resolved. In the first snippet `console.log(arr)` is included in the current function, in the second snippet it isn’t. – Sebastian Simon Jan 26 '22 at 06:21
  • `await` inside a loop when you want to run them serially. If in parallel, use `Promise.all` and `.map` – CertainPerformance Jan 26 '22 at 06:21
  • Does [this](https://stackoverflow.com/a/59695815/13658816) provide some relevant info? It is not comparing `for ... of` with `.map` but still provides useful info, I think. – jsN00b Jan 26 '22 at 06:22
  • This [blog](https://medium.com/@ExplosionPills/map-vs-for-loop-2b4ce659fb03) describes **map vs. for loop** – mukesh.kumar Jan 26 '22 at 06:24

0 Answers0