Skip to content

Instantly share code, notes, and snippets.

@loretoparisi
Created April 13, 2016 17:31
Show Gist options
  • Save loretoparisi/96b9fa3834aa4e0c3e220536a0c35152 to your computer and use it in GitHub Desktop.
Save loretoparisi/96b9fa3834aa4e0c3e220536a0c35152 to your computer and use it in GitHub Desktop.
Promise.settle implementation
// 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);
});
}));
}
@loretoparisi
Copy link
Author

see here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment