Asynchronous Process inside For loop (JS#1)

Saroj Subedi
2 min readMay 28, 2019

--

Let say we need to run asynchronous task inside For loop. Check this example below:

Guess the value of iprint by console. If you guess 0 & 1, then you are wrong.
Let me explain why.

The forloop runs immediately to complete. It will not wait the asynchronous operations to start or end.
When they complete some time in the future and call their callbacks, the value of your loop index variable iwill be at its last value for all the callbacks.

So the output will be 2 & 2.

There are two solutions for this problem.

  • Create a closure function and save loop index separately for each callback.
  • ES6 solution , use letto define variable of forloop. As letis blocked scope and uniquely defined for each iteration.

Check in live : https://jsbin.com/mawimehixa/1/edit?js,console

--

--

No responses yet