Promise.allLimitied = function(tasks = [], limit = 2) {
let queue = tasks.slice(0, limit);
let arr = [];
let num = 0;
return new Promise((resolve, reject) => {
function processMap() {
if (num === tasks.length) {
return resolve(arr);
}
}
function singlePromise(item, index) {
Promise.resolve(item).then(data => {
arr[index] = data;
num++;
processMap();
// 这种是真正的queue中的promise完成一个就会新触发一个tasks队列中的promise,之前那种实际是等到queue中所有的promise都完成了才一个一个触发,效率并不高
if (num < tasks.length && tasks[limit + num - 1]) {
singlePromise(tasks[limit + num - 1], limit + num - 1);
}
// 之前的方式
// if (num >= limit && tasks.length > num) {
// singlePromise(tasks[num], num);
// }
}, reject);
}
queue.forEach((item, index) => {
singlePromise(item, index);
});
});
};
function setPromise(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(num);
}, num * 10);
});
}
let p1 = setPromise(100);
let p2 = setPromise(200);
let p3 = setPromise(300);
let p4 = setPromise(400);
let p5 = setPromise(500);
let p6 = setPromise(600);
let p7 = setPromise(700);
let p8 = setPromise(800);
let p9 = setPromise(900);
let p10 = setPromise(1000);
console.time("time");
Promise.allLimitied([p10, p2, p3, p4, p5, p6, p7, p8, p9, p1], 5).then(data => {
console.log(data);
console.timeEnd("time");
});
Promise.all做并发限制
最新推荐文章于 2024-04-22 17:19:14 发布