Open Henry-Diasa opened 1 year ago
// countLimit 是一个函数,执行fn,执行的并发度是 2,返回一个 Promise
let countLimit = pLimit(fn, 2)
countLimit(a) // 立即执行
countLimit(b) // 立即执行
countLimit(c) // 前两个函数执行完再执行
// 求实现函数 pLimit
function pLimit(fn, times) {
let fns = []
function executeFns() {
if (fns.length && times) {
const f = fns.shift() ;
times--;
f().finally(() => {
times++;
executeFns()
})
} }
function inner(...args) {
fns.push(() => fn.apply(this, args));
executeFns()
}
return inner
};
let countLimit = pLimit(function (times) {
console.log('test', times);
return new Promise((resolve) => setTimeout(resolve, times * 1000))
}, 2);
countLimit(2);
countLimit(3);
countLimit(2);
countLimit(3);
countLimit(2);
countLimit(1)