官网链接
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为判断条件,满足就执行,适合没有数组只有循环次数的情况。