Salmon Salmon - 2 months ago 11
Javascript Question

Javascript, outside variable scope in callback function?

everyone.

I have a problem about the 'callback function - scope of variable',

I wanna use the 'i in for loop' to 'the callback function User_UidSearch',

but I cannot use it.

(I hope the solution don't use the global variable.)




Task_TidSearchExecution = function(tid, callback) {
var sql = "SELECT * FROM execution WHERE task = '" + tid + "'";
dbclient.query(sql, function (err, results) {
if (err || results.length <= 0)
callback(false);
else {
console.log(results.length);
for (var i = 0 ; i < results.length ; i++) {
User_UidSearch(results[i].employee, function (user) {
console.log(i);
// results[i]['email'] = user.email;
});
}

callback(results);
}
});
}


the "console.log(i);"

Recheck, this is wrong. -> Outputs are "undefined" of all.

undefined is "console.log(result[i]);"

But the "i" is keep '2' console twice, if results.length is 2.

I know becuz the for loop ending then execute the User_UidSearch,

but how can I slove the it "i" is 0 and 1.

Answer

You're dealing with closures, rewrite your code as follows:

...
(function(id) {
    User_UidSearch(results[id].employee, function (user) {
        console.log(id);
        // results[i]['email'] = user.email;
    });
})(i);

I.e. wrap your function to unbind i.

Comments