npm-async使用

时间:2022-08-17 06:03:48

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.whilst判断条件相反

async.doUntil(fn, test, callback)

  • async.doWhilst判断条件相反