async.series(tasks, callback)
tasks
能够是对象或数组,返回类型就是参数类型
tasks
中传入回调函数的第一个值非空即中止后面函数执行
- 按照顺序流程进行
async.series({
one: function (cb) {
cb(null, 'one')
},
two: function (cb) {
cb(null, 'two')
}
}, function (err, results) {
console.log(results);
})
async.waterfall(tasks, callback)
- 与
async.series
类型
tasks
中能够将结果向后传递
tasks
参数仅能够为数组
async.waterfall([function(cb) {
cb(null, 'one')
}, function (data, cb) {
cb(null, data + ' two')
}], function (err, results) {
console.log(results);
})
async.parallel(tasks, callback)
tasks
参数能够是数组或对象
tasks
函数所有并行执行
- 注意最终结果参数仍是按照
tasks
中声明的顺序
async.parallelLimit(tasks, limit, callback)
- 与
async.parallel
相同
limit
参数限制最大并发数量
async.queue(work, concurrency)
- 队列流程控制,增强版
paralle()
- 队列消息,限制
work
数量
- 参数
work
是执行任务的回调函数形式, concurrency
定义同时执行任务的数量
var async = require('async')
var count = 0;
var queue = async.queue(function (task, cb) {
console.log('work is processing task: ', task.name);
cb();
}, 2)
queue.push({name: 'one'}, function (err) {
setTimeout(function () {
console.log('finished processing foo');
}, 2000)
})
queue.push({name: 'two'}, function (err) {
setTimeout(function () {
console.log('finished processing two');
}, 1000)
})
queue.push({name: 'three'}, function (err) {
console.log('finished processing three');
})
queue.push({name: 'four'}, function (err) {
console.log('finished processing four');
})
//党最后一个任务交给work时调用,因此这里在name:four执行前调用
queue.empty = function () {
console.log('no more tasks wating');
}
//执行完全部任务后调用
queue.drain = function () {
console.log('all tasks have been processed');
}
async.whilst(test, fn, callback)
- 流程控制,至关于
while
- 适合以循环的方式执行异步操做
async.whilst(function () {
return count < 5
}, function (cb) {
count++;
setTimeout(function () {
cb(null, count)
}, 1000)
}, function (err, data) {
console.log(data);
})
async.doWhilst(fn, test, callback)
- 与
async.whilst
相似, 至关于do...while
语句
async.until(test, fn, callback)
async.doUntil(fn, test, callback)