p-limit限流任务

1,831 阅读1分钟
import pLimit from 'p-limit';

const limit = pLimit(1);  //限流个数

const datas = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];

 //限流任务
let loadDatas = [];
let count = 0;
const maxCount = datas.length;
_.forOwn(datas, data => {
    loadDatas.push(
        limit(() => this.handleConsole(data))
    );
    count += 1;
    if (maxCount === count) {
        (async () => {
	    await Promise.all(loadDatas);
        })();
    }
});
 
(async () => {
    // 按限流个数执行限流任务
    await Promise.all(loadDatas);
})();


handleConsole = (data) => {
    console.dir(data);
};

运行结果: 每次运行一个,运行完后运行下一个