function multiRequestWithLimit(payloadList, handler, limit = 3) {
const len = payloadList.length;
const result = new Array(len).fill(false);
let currentIndex = 0;
return new Promise((resolve, reject) => {
for (let i = 0; i < limit; i++) {
next();
}
function next() {
const index = currentIndex;
currentIndex++;
console.log("index", index);
if (!result.includes(false)) {
resolve(result);
}
if (index >= payloadList.length) {
return;
}
handler(payloadList[index])
.then((res) => (result[index] = res))
.catch((err) => (result[index] = err))
.then(next);
}
});
}
const payloadList = [1, 2, 3, 4];
const mapper = (value) =>
new Promise((resolve, reject) => setTimeout(() => resolve(value), 1000));
multiRequestWithLimit(payloadList, mapper).then((res) =>
console.log("res", res)
);