0

This is my code

for (var x in items) {
    var name = items[x].Name;
    var hotelID = 1;
    var sql = mysql.format('INSERT INTO Item(name, hotelID) VALUES(?, ?)', [name, hotelID]);
        con.query(sql, function (err, result) {
            if (err) {
                throw err;
            }
           //Below x is updated by the loop.
           console.log(item[x].Name);
        });

I want to get the value of x right before the con.query() call, but here the x is updated by the for loop before the callback is completed. How do i do that??

Aslam
  • 683
  • 1
  • 7
  • 20

1 Answers1

1

As you've identified, in a asynchronous callback "the x is updated by the for loop before the callback is completed".

The solution it to use the ES6 syntax let instead of var. Variables declared thus are correctly bound within the callback to the value they had when the callback was registered because a new variable is created for each iteration of the loop instead of using the single var which is hoisted to the top of the function.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • This would be a better answer if it explained *why* `let` acted that way (like the accepted answer on the duplicate question) – Quentin Jan 08 '18 at 15:00
  • @Quentin it would, but I don't actually know, I just know that it does :p NB, this is community wiki, so I'm not here for the rep. – Alnitak Jan 08 '18 at 15:06
  • "I don't actually know" — I just pointed you at an explanation, you could read it! – Quentin Jan 08 '18 at 15:07
  • @Quentin I did - it's not that great an explanation IMHO. I thought you were suggesting that there was something more mysterious about it than the scoping. – Alnitak Jan 08 '18 at 15:07