Created
February 17, 2021 04:18
-
-
Save brigand/c7e7d982b6628b9c0d9420740ada17e3 to your computer and use it in GitHub Desktop.
A slow async/await version of promiseMap
This file contains hidden or 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 promiseMap(array, mapper, concurrency) { | |
const promises = []; | |
const results = Array.from({ length: array.length }); | |
const drainOne = async () => { | |
const [pj, { index, resolved, rejected }] = await Promise.race(promises.map((p, pi) => p.then((v) => [pi, v]))); | |
promises.splice(pj, 1); | |
if (resolved) { | |
results[index] = resolved[0]; | |
} else { | |
throw rejected[0]; | |
} | |
} | |
for (const [i, item] of array.entries()) { | |
if (promises.length == concurrency) { | |
await drainOne(); | |
} | |
promises.push(mapper(item, i, array).then( | |
(resolved) => ({ index: i, resolved: [resolved] }), | |
(rejected) => ({ index: i, rejected: [rejected] }), | |
)); | |
} | |
while (promises.length) { | |
await drainOne(); | |
} | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment