Skip to content

Instantly share code, notes, and snippets.

@robinpokorny
Last active January 4, 2017 11:04
Show Gist options
  • Select an option

  • Save robinpokorny/f2a8a6628483f73d4fc71c9a61e51ca9 to your computer and use it in GitHub Desktop.

Select an option

Save robinpokorny/f2a8a6628483f73d4fc71c9a61e51ca9 to your computer and use it in GitHub Desktop.
Promise sequence fallback (first non-empty) – with Flow
// @flow
type Task<T> = (...args: any[]) => Promise<?T>
type Options<T> = {
args?: any[],
initial?: T,
isEmpty?: (value: ?T) => boolean
}
export default <T> (
tasks: Task<T>[],
options: Options<T> = {}
): Promise<?T> => {
const {
args = [],
initial,
isEmpty = (x) => !x
} = options
return tasks.reduce(
(prev, next) => prev.then((value) =>
isEmpty(value) ? next(...args) : value
),
Promise.resolve(initial)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment