Created
January 14, 2019 10:58
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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