nodejs async模块我常用的整理

官网链接
https://caolan.github.io/async/
安装:

npm install async

引用:

var async = require("async");

async 模块与 async await并不冲突,不用另起名引用
但是在 async模块里使用 await的时候就不用callbck了,直接return就行
官网的代码:

async.mapLimit(files, 10, async file => { // <- no callback!
    const text = await util.promisify(fs.readFile)(dir + file, 'utf8')
    const body = JSON.parse(text) // <- a parse error here will be caught automatically
    if (!(await checkValidity(body))) {
        throw new Error(`${file} has invalid contents`) // <- this error will also be caught
    }
    return body // <- return a value!
}, (err, contents) => {
    if (err) throw err
    console.log(contents)
})

maplimit

mapLimit(coll, limit, iteratee, callbackopt)
let  functiona=(pro, callback)=>{
	callback(null,xxx)
}
async.mapLimit(resources, 3, (pro, callback) => {
    functiona(pro, callback)
}, ( err,result) => {
    xxxxx
})

每次执行三个 functiona,coll可以为数组或json,但是为json的时候获取不到key值,只能得到里面的value
当所有的resources里所有的都循环一遍以后执行( err,result) => {xxxx}这个回调,
要注意的是若functiona里有一次传err过来(errmessage,null),就会马上执行回调后面的就循环不了了。
result 是每次传过来xxx的数组[xxx,xxx,xxx],
虽然resources每次循环的时候每个pro不一定是按顺序结束,但是result仍会按原来的顺序排列。


mapSeries

mapSeries(coll, iteratee, callbackopt)

同上,相当于 limit为1,一次执行一个。


mapValuesLimit

mapValuesLimit(obj, limit, iteratee, callbackopt)

async.mapValuesLimit({
    f1: 'file1',
    f2: 'file2',
    f3: 'file3'
},3, function (value, key, callback) {
  fs.stat(value, callback);
}, function(err, result) {
    // result is now a map of stats for each file, e.g.
    // {
    //     f1: [stats for file1],
    //     f2: [stats for file2],
    //     f3: [stats for file3]
    // }
});

没试过,貌似可以循环json ,可到key ,result 返回的是json。


whilst

whilst(test, iteratee, callbackopt)

var count = 0;
async.whilst(
    function test(cb) { cb(null, count < 5;) },
    function iter(callback) {
        count++;
        setTimeout(function() {
            callback(null, count);
        }, 1000);
    },
    function (err, n) {
        // 5 seconds have passed, n = 5
    }
);

test为判断条件,满足就执行,适合没有数组只有循环次数的情况。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值