Instantly share code, notes, and snippets.

Embed
What would you like to do?
Promise wrapper with state getters (isPending, isFulfilled, isRejected)
/*
* Create a new promise the same way as you would with the Promise constructor:
*
* let p = new PromiseWithState((res, rej) => {
* // ...
* });
*
* p.isPending(); // true
* p.isFulfilled(); // false
* p.isRejected(); // false
*
* Also works with Promise static methods:
*
* let p = PromiseWithState.resolve('foo');
*
* p.isPending(); // false
* p.isFulfilled(); // true
*/
const PromiseWithState = Object.setPrototypeOf(function(fn) {
let states = {
isPending: true,
isFulfilled: false,
isRejected: false
};
let p = new Promise(fn).then(
val => {
states.isFulfilled = true;
return val;
},
err => {
states.isRejected = true;
throw err;
}
).finally(() => {
states.isPending = false;
});
Object.keys(states).forEach(state => {
Object.defineProperty(p, state, {
enumerable: false,
get() {
return () => states[state];
}
});
});
return p;
}, Promise);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment