我真的很努力讓數組按照特定順序迭代,並且每個應該在下一個可以開始之前完成。我試過使用async.series和async.each,但結果並不像我期望的那樣。node.js 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:
我應該怎麼做,而不是得到預期的結果?
謝謝!
你必須調用'callback'異步! – Bergi