Last active
February 26, 2021 09:40
Traverse record of promises in parallel and give result of the same shape. (similar to sequenceRecord from purescript)
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 parMap = async <T, U>(array:T[], callback: (value: T) => U | PromiseLike<U>): Promise<U[]> => { | |
return Promise.all(array.map(callback)) | |
} | |
const parEach = async <T, U>(array:T[], callback: (value: T) => void | PromiseLike<void>): Promise<void> => { | |
await Promise.all(array.map(callback)) | |
} | |
async function main() { | |
const names = ["foo.txt","baz.txt"] | |
// const result: string[][] | |
const result = await parMap(names, (name) => Promise.resolve([name,name,name])) | |
} |
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
type AnyRecord = Record<keyof object, any> | |
type UnPromise<T> = T extends PromiseLike<infer R> ? R: T | |
const parRecord = <T extends AnyRecord>(r : T): Promise<{ [K in keyof T]: UnPromise<T[K]> }> => | |
Promise.all(Object.values(r)) | |
.then( | |
(results) => Object.fromEntries( | |
Object.keys(r) | |
.map( | |
(key,idx) => [key, results[idx]] | |
) | |
) | |
) as any | |
async function main() { | |
// const x: { | |
// user: { name: string }; | |
// avatar: string; | |
// age: number; | |
// } | |
const x = await parRecord({ | |
user: Promise.resolve({name:"irakli"}), | |
avatar: Promise.resolve(":)"), | |
age: 25, | |
}) | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment