stackoverflow/js/promiseHelpers.js

18 lines
635 B
JavaScript
Raw Normal View History

2024-09-12 10:11:53 +10:00
async function allSettledConcurrent(items, concurrency, fn) {
const results = new Array(items.length);
const queue = items.map((item, index) => ({ item, index }));
const doFn = async ({ item, index }) => {
try {
const value = await fn(item);
results[index] = { value, status: "fulfilled" };
} catch (reason) {
results[index] = { reason, status: "rejected" };
}
return queue.length && doFn(queue.shift());
};
const slots = queue.splice(0, concurrency).map(doFn);
await Promise.all(slots);
return results;
}
export { allSettledConcurrent };