Promise rate limiter
function limit(tasks, concurrency) {
const results = [];
async function runTasks(tasksIterator) {
for (const [index, task] of tasksIterator) {
try {
results[index] = await task();
} catch (error) {
results[index] = new Error(`Failed with: ${error.message}`);
}
}
}
// fill the same iterator
const iterator = tasks.entries()
const workers = new Array(concurrency)
.fill(iterator)
.map(runTasks);
await Promise.allSettled(workers);
return results;
}