Skip to content

Instantly share code, notes, and snippets.

@matthieuprat
Last active December 15, 2015 12:18
Show Gist options
  • Save matthieuprat/71bfe85f54a108d3b13f to your computer and use it in GitHub Desktop.
Save matthieuprat/71bfe85f54a108d3b13f to your computer and use it in GitHub Desktop.
/**
* 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