Last active
June 20, 2019 21:29
-
-
Save smockle/a1ffe76b351425e8ba3d390fb4fb199d to your computer and use it in GitHub Desktop.
Bluebird.prototype.map with native Promises
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
#!/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