Correct Writing
suggest changevar pipeline = {};
// (...) adding things in pipeline
var processOneFile = function(key) {
fs.stat(pipeline[key].path, function(err, stats) {
if (err) {
// clear that one
delete pipeline[key];
return;
}
// (...)
pipeline[key].count++;
});
};
// verify it is not growing
for(var key in pipeline) {
processOneFile(key);
}
processOneFile takes key as a parameter, and the fs.stat callback closes over that parameter. Each call gets its own binding, so the callbacks do not share the for loop’s key. With var, closing over the loop variable itself would make every callback see the same key. This example assumes Node.js fs and a pipeline object filled in above.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents