Last active
January 4, 2017 11:04
-
-
Save robinpokorny/f2a8a6628483f73d4fc71c9a61e51ca9 to your computer and use it in GitHub Desktop.
Promise sequence fallback (first non-empty) – with Flow
This file contains hidden or 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
| // @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