function sleep(delay) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(delay)
}, delay);
})
}
Promiseall = function(promises, max) {
let curLen = 0;
let maxLen = max;
let queue = [];
let pLen = promises.length;
let complete = 0;
let results = new Array(pLen);
return new Promise((resolve, reject) => {
function run() {
while (curLen < maxLen && queue.length) {
const {promise, i} = queue.shift();
curLen++;
promise.then((value) => {
console.log(value);
results[i] = value;
complete++;
curLen--;
if (complete === pLen) {
resolve(results);
}
run();
}).catch((error) => {
reject(error);
});
}
}
promises.forEach((promise, i) => {
queue.push({promise, i});
run();
})
})
}
const promises = [sleep(2000), sleep(1000), sleep(4000), sleep(3000)];
Promiseall(promises, 2).then((results) => {
console.log(results);
})
console