Skip to content

Instantly share code, notes, and snippets.

@eschwartz
Last active September 7, 2017 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eschwartz/565e92418d903b7e98dd7bb9679293c1 to your computer and use it in GitHub Desktop.
Save eschwartz/565e92418d903b7e98dd7bb9679293c1 to your computer and use it in GitHub Desktop.
Run a set of async fns in sequence
/**
* 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([]));
}
/**
* 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;
@eschwartz
Copy link
Author

eg

sequence([
  () => Promise.resolve(1),
  () => Promise.resolve(2),
  () => Promise.resolve(3),
  () => Promise.resolve(4),
])
  .then(res => {
     // res === [1, 2, 3, 4]
  })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment