Skip to content

Instantly share code, notes, and snippets.

@smockle
Last active June 20, 2019 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smockle/a1ffe76b351425e8ba3d390fb4fb199d to your computer and use it in GitHub Desktop.
Save smockle/a1ffe76b351425e8ba3d390fb4fb199d to your computer and use it in GitHub Desktop.
Bluebird.prototype.map with native Promises
#!/usr/bin/env node
//@ts-check
const MAX_CONCURRENCY = 3;
function sayHiAsync() {
console.log("marco");
return new Promise((resolve) => {
console.log("polo");
setTimeout(() => {
console.log("bravo");
resolve("Hi!");
}, 2000)
})
}
async function concurrentPromises(inputs, promiseFactory, concurrency) {
try {
let results = [];
while (inputs.length > 0) {
const iterationInputs = inputs.splice(0, Math.min(inputs.length, concurrency));
const iterationPromises = iterationInputs.map((input) => promiseFactory(input));
console.log(`Evaluating: ${iterationPromises.length}. Evaluated: ${results.length}. Remaining: ${inputs.length}.`);
const iterationResults = await Promise.all(iterationPromises);
console.log(iterationResults);
results = results.concat(iterationResults);
}
return results;
} catch (error) {
throw error;
}
}
(async () => {
const recipients = Array.from(new Array(10));
let results = await concurrentPromises(recipients, sayHiAsync, MAX_CONCURRENCY);
results.forEach((result) => console.log(result));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment