Below are examples that I see in practice a lot. Let’s st
In this case, console.log will always be 5. This is because ‘for loop’ doesn’t wait for the API call to finish and when the first response comes back, the loop has ended. You can also see that in the image above.
And to fix them there are many ways but I use (IIFE), one of the possible fixes for this is to create a closure for each loop so we can keep the loop’s index for each call. API.
We can use the immediately called function expression (IIFE), with which we will pass our index.
This is a function that will call itself and run immediately. You can see the image below.
I don’t know what the developers think, but I think this is ok, but since let was born I have seen a difference, and this is the difference.
Fortunately, with ‘let’ we don’t need to do that.
We can just declare ‘i’ in the loop with the keyword ‘let’ instead of ‘var’ and this will fix it for us. Picture below.
Thank you for watching.