我真的很难按特定顺序迭代数组,每一个都应该在下一个开始之前完成。我尝试过使用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:
我该怎么办才能获得预期的结果?
谢谢!
答案 0 :(得分:2)
async.each
并行发生,因此所有这些函数都会同时运行。您正在寻找async.eachSeries
方法:https://www.npmjs.com/package/async#eachseries-arr-iterator-callback
与每个相同,只有迭代器应用于arr中的每个项目。只有当前的迭代器完成后才会调用下一个迭代器。这意味着迭代器函数将按顺序完成。
答案 1 :(得分:2)
将所有这些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);
}
});