錯誤的程式碼你能發現為什麼金鑰的使用會導致錯誤
var 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++;
});
}
問題是 var key 只有一個例項。所有回撥都將共享相同的金鑰例項。在回撥將觸發時,該鍵很可能已經增加,而不是指向我們接收統計資料的元素。