Last active
May 4, 2018 12:48
-
-
Save ttristan/f61779a3e1c5f66d908069502181c8ab to your computer and use it in GitHub Desktop.
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
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