-
-
Save jaawerth/291a998094b2c813326dcae9c698143a to your computer and use it in GitHub Desktop.
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
'use strict'; | |
async function promiseMap(promisesOrValues, mapper, { concurrency = Infinity } = {}) { | |
if (!Number.isInteger(concurrency)) { | |
throw new TypeError(`concurrency must be an integer, got ${typeof concurrency}: ${concurrency}`); | |
} | |
if (concurrency < 1) { | |
throw new RangeError(`concurrency must be greater than 0, got ${concurrency}`); | |
} | |
const results = []; | |
for (let i = 0; i < promisesOrValues.length; i = i + concurrency) { | |
const batch = promisesOrValues.slice(i, i + concurrency) | |
.map(pVal => Promise.resolve(pVal).then(val => mapper(val, i, promisesOrValues))); | |
const batchResults = await Promise.all(batch); | |
results.push(...batchResults); | |
} | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment