Last active
October 25, 2021 17:43
-
-
Save assertnotnull/8deb6f33d5c572612797f32a8e6df1c8 to your computer and use it in GitHub Desktop.
Map 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
import R from 'ramda' | |
export async function mapAsync<Type, ReturnedType>( | |
promiseFunc: (value: Type) => Promise<ReturnedType>, | |
values: Type[], | |
chunk = 3 | |
) { | |
const processChunk = processWithFunction<Type, ReturnedType>(promiseFunc) | |
const chunks = R.splitEvery(chunk, values) | |
return R.flatten(await R.reduce(processChunk, Promise.resolve([]), chunks)) | |
} | |
function processWithFunction<Type, ReturnedType>(promiseFunc: (x: Type) => Promise<ReturnedType>) { | |
return async (acc: Promise<ReturnedType[]>, chunkOfValues: Type[]) => { | |
const resolved = await acc | |
const outcome = await Promise.all(chunkOfValues.map((chunk) => promiseFunc(chunk))) | |
resolved.push(...outcome) | |
return resolved | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment