Asynchronous Process inside For loop (JS#1)
2 min readMay 28, 2019
Let say we need to run asynchronous task inside For loop. Check this example below:
Guess the value of i
print by console. If you guess 0 & 1, then you are wrong.
Let me explain why.
The for
loop 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 i
will 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
let
to define variable offor
loop. Aslet
is blocked scope and uniquely defined for each iteration.
Check in live : https://jsbin.com/mawimehixa/1/edit?js,console