Skip to content

Instantly share code, notes, and snippets.

@ttristan
Last active May 4, 2018 12:48
Show Gist options
  • Save ttristan/f61779a3e1c5f66d908069502181c8ab to your computer and use it in GitHub Desktop.
Save ttristan/f61779a3e1c5f66d908069502181c8ab to your computer and use it in GitHub Desktop.
exports.reducePromises = (fns = []) =>
fns.reduce(
(promise, fn) =>
promise.then(result => {
return fn(result)
.then(Array.prototype.concat.bind(result))
.catch(Array.prototype.concat.bind(result));
}),
Promise.resolve([])
);
// example
const promise1 = () => new Promise(resolve => resolve(1));
const promise2 = () => new Promise(resolve => resolve(2));
const promise3 = () => new Promise((resolve, reject) => reject(3));
const promise4 = iNeedPrevResults => {
iNeedPrevResults.forEach(prevRes => console.log("prevRes:", prevRes));
return new Promise(resolve => resolve(4));
};
// usage
exports
.reducePromises([promise1, promise2, promise3, promise4])
.then(resultCollection => {
console.log("resultCollection", resultCollection);
})
.catch(err => console.log("error", err));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment