Erroneous code: why this use of key leads to bugs
suggest changevar pipeline = {};
// (...) adding things in pipeline
for(var key in pipeline) {
fs.stat(pipeline[key].path, function(err, stats) {
if (err) {
// clear that one
delete pipeline[key];
return;
}
// (...)
pipeline[key].count++;
});
}
There is only one key binding because the loop uses var. Every fs.stat callback closes over that same binding. for...in assigns the next property name to key; it does not increment it. By the time a callback runs, key is usually the last name the loop assigned, not the name from the iteration that started that call. This example assumes Node.js fs. The fix is a per-call binding, as in Correct Writing.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents