Created
June 10, 2019 02:21
-
-
Save aleclarson/11157b065748b3577a83d75f2e01db24 to your computer and use it in GitHub Desktop.
Run an async action in topological order (dependencies run first)
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
export const runTopological = <T>( | |
packages: PackageJson[], | |
action: (pkg: PackageJson) => Promise<T> | |
): Promise<T[]> => { | |
const promises: Promise<T>[] = [] | |
const run = (pkg: PackageJson, i: number) => | |
promises[i] || | |
(promises[i] = Promise.all( | |
Object.keys(pkg.dependencies || {}).map(name => { | |
const i = packages.findIndex(pkg => pkg.name === name) | |
return i >= 0 && run(packages[i], i) | |
}) | |
).then(() => action(pkg))) | |
packages.forEach(run) | |
return Promise.all(promises) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment