Skip to content

Instantly share code, notes, and snippets.

@aleclarson
Created June 10, 2019 02:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aleclarson/11157b065748b3577a83d75f2e01db24 to your computer and use it in GitHub Desktop.
Save aleclarson/11157b065748b3577a83d75f2e01db24 to your computer and use it in GitHub Desktop.
Run an async action in topological order (dependencies run first)
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