Take the code below, in which an object data
is initialized with some values that are then processed by some time-intensive function, like database access. If the function succeeds, the name of the successful data
item is printed to the console. Otherwise, a failure notice is printed:
data = {first: 'someinfo', second: 'somemoreinfo', third: 'evenmoreinfo'};
for (var item in data) {
timeIntensiveFunction(item, data[item], function(err) {
if (!err) {
console.log(item + ' processed successfully');
} else {
console.log(item + ' failed');
}
});
}
You would expect the console to show this, assuming the function succeeds for all three data items:
first processed successfully
second processed successfully
third processed successfully
Instead it will show this, assuming the first database access takes longer than the for
loop:
third processed successfully
third processed successfully
third processed successfully
This is because the console logging is done in a callback, which would reasonably only be called after the for
loop is done, because timeIntensiveFunction()
takes so long. By the time the first callback is called, item
already has its last value, third
.
How do you pass the 'current' value of item into the callback?