Created
February 17, 2019 11:13
-
-
Save Xetera/f384978991364ca08d71ccdb7c7e1dc1 to your computer and use it in GitHub Desktop.
Mapping an array asynchronously with maximum N number of concurrent requests
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
const parallelMap = (arr, fn, max) => { | |
const out = []; | |
const initial = [...Array(max)]; | |
const fired = initial.map(() => Promise.resolve().then(async function cb() { | |
if (!arr.length) return | |
const next = arr.shift(); | |
out.push(await fn(next)); | |
return cb(); | |
})); | |
return Promise.all(fired).then(() => out); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment