Skip to content

Instantly share code, notes, and snippets.

@andrew8088
Created February 15, 2024 14:56
Show Gist options
  • Select an option

  • Save andrew8088/7ecdf23aab7412fe9c702f8ca0387768 to your computer and use it in GitHub Desktop.

Select an option

Save andrew8088/7ecdf23aab7412fe9c702f8ca0387768 to your computer and use it in GitHub Desktop.
Managing Promise Concurrency in JavaScript
function mapPromises(args, callback, concurrency = 3) {
const { promise, resolve } = Promise.withResolvers();
const results = [];
let cursor = 0;
function next() {
if (cursor < args.length) {
const index = cursor++;
void callback(...args[index]).then(value => {
results[index] = { status: 'fulfilled', value };
}).catch(reason => {
results[index] = { status: 'rejecte', reason };
}).then(() => {
setImmediate(next);
});
} else if (args.length === results.length) {
resolve(results);
} else {
// no args remaining, but pending promises - just wait
}
}
while (concurrency--) {
next();
}
return promise;
}
@lnfel

lnfel commented Feb 15, 2024

Copy link
Copy Markdown

promise withResolvers FTW!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment