Last active
December 15, 2015 12:18
-
-
Save matthieuprat/71bfe85f54a108d3b13f 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
/** | |
* Returns a promise that is fulfilled with an array of promise state | |
* snapshots, but only after all the original promises have settled, i.e. | |
* become either fulfilled or rejected. | |
* | |
* See https://github.com/kriskowal/q/wiki/API-Reference#promiseallsettled | |
*/ | |
allSettled = (promises) => { | |
let resolve, outer = new Promise((r) => { resolve = r }) | |
let snapshots = [], settledCount = 0 | |
let handler = (index, state, value) => { | |
snapshots[index] = { | |
state, | |
[state === 'fullfiled' ? 'value' : 'reason']: value | |
} | |
// Resolve the outer promise if all the original promises have settled. | |
promises.length === ++settledCount && resolve(snapshots) | |
} | |
promises.forEach(function (promise, index) { | |
promise.then( | |
handler.bind(null, index, 'fullfiled'), | |
handler.bind(null, index, 'rejected') | |
) | |
}) | |
return outer | |
} | |
allSettled([Promise.resolve('foo'), Promise.reject('bar')]) | |
.then((snapshots) => { | |
console.log.apply(console, snapshots) | |
}) | |
// Object {state: "fullfiled", value: "foo"} Object {state: "rejected", reason: "bar"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment