var async = require('async');
function callbackhandler(err, results) {
console.log('It came back with this ' + results);
}
function takes5Seconds(callback) {
console.log('Starting 5 second task');
setTimeout( function() {
console.log('Just finshed 5 seconds');
callback(null, 'five');
}, 5000);
}
function takes2Seconds(callback) {
console.log('Starting 2 second task');
setTimeout( function() {
console.log('Just finshed 2 seconds');
callback(null, 'two');
}, 2000);
}
async.series([takes2Seconds(callbackhandler),
takes5Seconds(callbackhandler)], function(err, results){
console.log('Result of the whole run is ' + results);
})
输出如下所示:
Starting 2 second task
Starting 5 second task
Just finshed 2 seconds
It came back with this two
Just finshed 5 seconds
It came back with this five
我希望take2Second函数在take5Second开始之前完全完成。 它是如何工作的。请告诉我。 而最终的功能永远不会运行。谢谢。
答案 0 :(得分:38)
不完全。您正在立即执行这些函数(一旦评估了数组),这就是它们似乎同时启动的原因。
传递给每个要执行的函数的回调是异步库的内部。一旦函数完成,执行它,传递错误和/或值。您不需要自己定义该功能。
最后的函数永远不会在你的情况下运行,因为async需要你调用以回到系列中的下一个函数的回调函数从未实际执行过(只有你的callbackHandler
函数被执行)。
请改为尝试:
async.series([
takes2Seconds,
takes5seconds
], function (err, results) {
// Here, results is an array of the value from each function
console.log(results); // outputs: ['two', 'five']
});
答案 1 :(得分:15)
詹姆斯给了你一个关于async.series
的概述。请注意,您可以在系列数组中设置匿名函数,然后使用参数
var async = require('async')
var param1 = 'foobar'
function withParams(param1, callback) {
console.log('withParams function called')
console.log(param1)
callback()
}
function withoutParams(callback) {
console.log('withoutParams function called')
callback()
}
async.series([
function(callback) {
withParams(param1, callback)
},
withoutParams
], function(err) {
console.log('all functions complete')
})
答案 2 :(得分:9)
创建异步系列的首选方法是使用操作数组,如下所示;
var async = require('async'),
operations = [];
operations.push(takes2Seconds);
operations.push(takes5seconds);
async.series(operations, function (err, results) {
// results[1]
// results[2]
});
function takes2Seconds(callback) {
callback(null, results);
}
function takes5seconds(callback) {
callback(null, results);
}
答案 3 :(得分:6)
async.series
([
function (callback)
{
response=wsCall.post(user,url,method,response);
console.log("one");
callback();
}
,
function (callback)
{
console.log("two");
//console.log(response);
callback();
}
]
,
function(err)
{
console.log('Both a and b are saved now');
console.log(response);
});
答案 4 :(得分:2)
在async.series
中,所有函数都是串行执行的,每个函数的合并输出都传递给最终的回调函数。 e.g
var async = require('async');
async.series([
function (callback) {
console.log('First Execute..');
callback(null, 'userPersonalData');
},
function (callback) {
console.log('Second Execute.. ');
callback(null, 'userDependentData');
}
],
function (err, result) {
console.log(result);
});
输出:
First Execute..
Second Execute..
['userPersonalData','userDependentData'] //result