Created
April 13, 2016 17:31
-
-
Save loretoparisi/96b9fa3834aa4e0c3e220536a0c35152 to your computer and use it in GitHub Desktop.
Promise.settle implementation
This file contains hidden or 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
// ES6 version of settle | |
Promise.settle = function(promises) { | |
function PromiseInspection(fulfilled, val) { | |
return { | |
isFulfilled: function() { | |
return fulfilled; | |
}, isRejected: function() { | |
return !fulfilled; | |
}, isPending: function() { | |
// PromiseInspection objects created here are never pending | |
return false; | |
}, value: function() { | |
if (!fulfilled) { | |
throw new Error("Can't call .value() on a promise that is not fulfilled"); | |
} | |
return val; | |
}, reason: function() { | |
if (fulfilled) { | |
throw new Error("Can't call .reason() on a promise that is fulfilled"); | |
} | |
return val; | |
} | |
}; | |
} | |
return Promise.all(promises.map(function(p) { | |
// make sure any values are wrapped in a promise | |
if (!Promise.isPromise(p)) { | |
p = Promise.resolve(p); | |
} | |
return p.then(function(val) { | |
return new PromiseInspection(true, val); | |
}, function(err) { | |
return new PromiseInspection(false, err); | |
}); | |
})); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
see here.