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.
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
letis blocked scope and uniquely defined for each iteration.
Check in live : https://jsbin.com/mawimehixa/1/edit?js,console