Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save batrudinych/f9e54a3b6d75ce6594d9136c9570ba6e to your computer and use it in GitHub Desktop.
Save batrudinych/f9e54a3b6d75ce6594d9136c9570ba6e to your computer and use it in GitHub Desktop.
Running async operations in parallel and harvesting the results. Concurrency limit applied correctly
async function take3subtake1part1() {
const concurrencyLimit = 5;
// Enhance arguments array to have an index of the argument at hand
const argsCopy = [].concat(listOfArguments.map((val, ind) => ({ val, ind })));
const result = new Array(listOfArguments.length);
const promises = new Array(concurrencyLimit).fill(Promise.resolve());
// Recursively chain the next Promise to the currently executed Promise
function chainNext(p) {
if (argsCopy.length) {
const arg = argsCopy.shift();
return p.then(() => {
// Store the result into the array upon Promise completion
const operationPromise = asyncOperation(arg.val).then(r => { result[arg.ind] = r; });
return chainNext(operationPromise);
});
}
return p;
}
await Promise.all(promises.map(chainNext));
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment