我的理解:解决异步编程,减少回调的嵌套 目前较好用的库
async引入:import * as async from 'async';
//多个函数依次执行,之间没有数据交换,简版的async.waterfall
async.series(
[
(next: Function) => {
console.log('series1');
next();
},
(next: Function) => {
console.log('series1');
next();
}
],
(err: Error) => {
if (err) {
console.log(err);
}
console.log('all series');
}
);
//多个函数依次执行,且前一个的输出为后一个的输入,即每一个函数产生的值,都将传给下一个函数。
//如果中途出错,后面的函数将不会被执行。错误信息以及之前产生的结果,将传给 waterfall 最终的 callback。
async.waterfall(
[
(next: Function) => {
console.log('waterfall1');
next(1);
},
(data: any, next: Function) => {
console.log('waterfall2 data=' + data);
next(null);
}
],
(err: Error) => {
if (err) {
console.log(err);
}
console.log('all waterfall');
}
);
//多个函数并行执行,每个函数都是立即执行,不需要等待其它函数先执行
async.parallel(
[
(next: Function) => {
console.log('parallel1');
next();
},
(next: Function) => {
console.log('parallel2');
next();
},
],
(err: Error) => {
if (err) return;
console.log('all parallel');
}
);
//多个函数有依赖关系,有的并行执行,有的依次执行 这里的意思是bg和skip同时执行,等待两者都执行完才会走到allFinish
//详见帖子:
async.auto(
{
bg: (bgFinish) => {
console.log('autoFinish1');
bgFinish();
},
skip: (skipFinish) => {
console.log('autoFinish2');
skipFinish();
},
},
(err: Error) => {
if (err) {
console.log(err);
}
console.log('auto all Finish');
}
);
//一些工具
//async.forever(fn,callback) 跟它名字一样,fn一直循环执行,直到程序出现异常,例子中a=10时,停止循环
let a = 0;
async.forever(
function (callback) {
setTimeout(function () {
console.log(a++);
if (a == 10) {
callback('err', 0);
} else {
callback(null, 1);
}
}, 1000);
},
function (err) {
console.log(err);
}
);
//遍历数组的每一项
let list = [1, 2, 3];
async.foreach(list, (data: any) => { console.log(data); });
//async.eachOfSeries 对数组的每一项做异步操作
async.eachOfSeries(
list,
(idx: number, next: Function) => {
next();
},
(err) => {
console.log(err);
}
);