Skip to content

Instantly share code, notes, and snippets.

@psenger
Last active February 1, 2020 00:08
Show Gist options
  • Save psenger/b21ba0f70bdb59839d5838966c537671 to your computer and use it in GitHub Desktop.
Save psenger/b21ba0f70bdb59839d5838966c537671 to your computer and use it in GitHub Desktop.
[Promise Design Patterns for serial actions] #JavaScript #Promise
/**
* Sequentially execute an array of functions that return promises.
* @example:
* .then((data)=>{
* const functions = data.map( (body) => {
* return () => {
* return requestPromise({
* method: 'PATCH',
* uri: `${HOST}:${PORT}/update`,
* headers: {Authorization: `JWT ${token}`},
* json: body,
* })
* }
* } );
* return promiseSerial(functions);
* })
* @param {function[]} functions - An array of functions tha return promises.
*/
const promiseSerial = ( functions ) => {
return functions.reduce((promise, func) => {
return promise.then(result => func().then(Array.prototype.concat.bind(result)))
}, Promise.resolve([]));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment