Last active
September 7, 2017 19:57
-
-
Save eschwartz/565e92418d903b7e98dd7bb9679293c1 to your computer and use it in GitHub Desktop.
Run a set of async fns in sequence
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
/** | |
* Run a series of async functions in sequence, | |
* so that each fn waits to run until the last one has completed. | |
* | |
* @param {function():Promise<T>} fns | |
* @returns {Promise<T[]> | |
*/ | |
function sequence(fns) { | |
return fns | |
.reduce((_prevResults, fn) => ( | |
_prevResults.then( | |
prevResults => fn().then(res => prevResults.concat([res])) | |
) | |
), Promise.resolve([])); | |
} |
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
/** | |
* Run a series of async functions in sequence, | |
* so that each fn waits to run until the last one has completed. | |
*/ | |
function sequence<TRes>(fns:IAsyncFn<TRes>[]):Promise<TRes[]> { | |
return fns | |
.reduce((_prevResults:Promise<TRes[]>, fn) => ( | |
_prevResults.then( | |
prevResults => fn().then(res => prevResults.concat([res])) | |
) | |
), Promise.resolve([])); | |
} | |
export interface IAsyncFn<TRes> { | |
():Promise<TRes> | |
} | |
export default sequence; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
eg