Newbie alert!
I'm trying to understand the variable scope for a promise inside a for loop.
Consider the following code:
function sleep(ms) {
return new Promise(resolve =>
setTimeout(resolve, ms)
);
}
for (var i =0; i<4; i++){
sleep(1000).then(() => console.log(i));
}
The promise is called 4 times at once and then responds with:
4
4
4
4
How can I keep reference to the i variable? In order to get
0
1
2
3
Or whatever execution order actually took place.