好用的第三方库async

我的理解:解决异步编程,减少回调的嵌套 目前较好用的库

async引入:import * as async from 'async';

async文档:https://caolan.github.io/async/v3/

//多个函数依次执行,之间没有数据交换,简版的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);
    }
);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值