我正在尝试更改一个没有任何控制流的工作代码,以便在完成所有操作后进行多少更改。没有控制流程,这是不可能的。
要这样做,我正在尝试异步,但我在这里有点困惑。
旧代码:
public static populate(){
// Read all files inside the populate folder.
fs.readdir(__config.path.populate, function(err, files){
if(err){
consoleDev(err);
}else{
// For each file, get the data to populate stored in the file.
_.each(files, function(file){
_.each(require(__config.path.base + __config.path.populate + file), function(documents){
// The file name must be the same as the targeted model.
var Model = __Dao.getModel(file.split('.')[0]);// Filter the extension.
if(Model){
// For each data, try to add it if it does not exist in the DB.
Model.findOrCreate(documents, function(err, doc, created){
if(created){
consoleDev('The following document was created in the [' + Model.modelName + '] collection: ' + JSON.stringify(doc));
}
});
}else{
consoleDev('Unable to populate the file: ' + file + '. The model was not found.')
}
});
});
}
});
}
新代码:
public static populate(){
// Read all files inside the populate folder.
fs.readdir(__config.path.populate, function(err, files){
if(err){
consoleDev(err);
}else{
_.each(files, function(file){
// Read all files in async mode with control flow.
async.each(require(__config.path.base + __config.path.populate + file), function(documents, callback){
// The file name must be the same as the targeted model.
var Model = __Dao.getModel(file.split('.')[0]);// Filter the extension.
if(Model){
// For each data, try to add it if it does not exist in the DB.
Model.findOrCreate(documents, function(err, doc, created){
if(created){
consoleDev('The following document was created in the [' + Model.modelName + '] collection: ' + JSON.stringify(doc));
Populate._added++;
}else{
Populate._read++;
}
callback();
});
}else{
callback('Unable to populate the file: ' + file + '. The model was not found.')
}
});
}, function(err){
if(err){
console.log(err);
}
consoleDev(Populate._added + ' documents were added. There are now ' + Populate._read + ' + ' + Populate._added + ' = ' + (Populate._read + Populate._added) + ' documents populated.');
});
}
});
}
最后在控制台上没有显示任何内容,我在控制台上没有任何错误。该脚本仍然有效,并且之前添加了DB中不存在的文档。但我仍然没有留言说我添加了多少。
我试图改为async.each(files, function(file, callback){
,但收到错误Error: Callback was already called.
。
我在这里缺少什么?