Why does this callback not have access to the correct value of the outer scope?

Using node-mysql I have the following code:

for (var i = 0; i < 10; i++) {
    connection.query('select 1', function(err, rows) {
        console.log('#' + i);
    });
}

I expected the result to be # 0, # 1, ..., # 9, but the actual result of 10 will be printed 10 times. Obviously, it prints the value iat the time the callback was executed instead of creating the callback. How to realize the desired result?

+4
source share
1 answer

I declare with let:

var i => let i

for (let i = 0; i < 10; i++) {
+5
source

Source: https://habr.com/ru/post/1691426/


All Articles