node.js与async.each async.series不按预期方式执行

我真的很努力获得以特定顺序迭代的数组,并且每个应该在下一个可以开始之前完成。 我试过使用async.series和async.each,但结果并不像我预期的那样。

我有这个代码:

var async = require('async'); var abc = ['a', 'b', 'c']; // Step 1 function one(callback) { async.each(abc, function(issue, callback) { setTimeout(function(){ issue += '1'; console.log('Processing issue ' + issue); }, 2000); callback(); }, function(err) { if(err) { console.log('Fail 1'); } else { console.log('Success 1'); } }); } // Step 2 function two(callback) { async.each(abc, function(issue, callback) { setTimeout(function(){ issue += '2'; // Perform operation on file here. console.log('Processing issue ' + issue); }, 2000); callback(); }, function(err) { if(err) { console.log('Fail 2'); } else { console.log('Success 2'); } }); } // Step 3 function three(callback) { async.each(abc, function(issue, callback) { setTimeout(function(){ issue += '3'; // Perform operation on file here. console.log('Processing issue ' + issue); }, 2000); callback(); }, function(err) { if(err) { console.log('Fail 3'); } else { console.log('Success 3'); } }); } async.series([ function(callback) { console.log('step 1 in async.series'); one(callback); callback(); }, function(callback) { console.log('step 2 in async.series'); two(callback); callback(); }, function(callback) { console.log('step 3 in async.series'); three(callback); callback(); } ], function(err) { if(err) return next(err); console.log('Done:'); }); 

结果:

 step 1 in async.series Success 1 step 2 in async.series Success 2 step 3 in async.series Success 3 Done: //After two second timeout all below happens at once Processing issue a1 Processing issue b1 Processing issue c1 Processing issue a2 Processing issue b2 Processing issue c2 Processing issue a3 Processing issue b3 Processing issue c3 

预期:

 step 1 in async.series //Expected below after two second timeout Processing issue a1 Processing issue a2 Processing issue a3 Success 1 step 2 in async.series //Expected below after two+two second timeout Processing issue b1 Processing issue b2 Processing issue b3 Success 2 step 3 in async.series //Expected below after two+two+two second timeout Processing issue c1 Processing issue c2 Processing issue c3 Success 3 Done: 

我应该做什么,而不是得到预期的结果?

谢谢!

       

网上收集的解决方案 "node.js与async.each async.series不按预期方式执行"

async.each并行发生,所有这些函数都会同时运行。 您正在寻找async.eachSeries方法: https : async.eachSeries

与每个相同,只有迭代器被应用于arr中的每个项目。 下一个迭代器只在当前迭代器完成时调用。 这意味着迭代器函数将按顺序完成。

把所有这些callback函数()放入setTimeout()中。 那么一切都应该如你所愿。

编辑:每一步应该看起来像这样:

 // Step 1 function one(done) { console.log('step 1 in async.series'); async.each(abc, function(issue, callback) { setTimeout(function(){ issue += '1'; console.log('Processing issue ' + issue); callback(); }, 2000); }, done); } 

而实际的系列应该是这样的:

 async.series([one, two, three], function(err, data){ if (err !== null) { console.log(data); } else { console.error(err); } });