Skip to content

Instantly share code, notes, and snippets.

@assertnotnull
Last active October 25, 2021 17:43
Show Gist options
  • Save assertnotnull/8deb6f33d5c572612797f32a8e6df1c8 to your computer and use it in GitHub Desktop.
Save assertnotnull/8deb6f33d5c572612797f32a8e6df1c8 to your computer and use it in GitHub Desktop.
Map promises
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