npm-async使用

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判断条件相反
相关文章
相关标签/搜索