Skip to content

Instantly share code, notes, and snippets.

@goodevilgenius
Created August 21, 2023 15:16
Show Gist options
  • Save goodevilgenius/b7d90010763fc5244b0c9b71b44b1ee5 to your computer and use it in GitHub Desktop.
Save goodevilgenius/b7d90010763fc5244b0c9b71b44b1ee5 to your computer and use it in GitHub Desktop.
A javascript promise that can tell you if it's been fulfilled.
Promise.prototype.getQueryable = function () {
if (this.isFulfilled) return this;
let isPending = true;
let isRejected = false;
let isFulfilled = false;
let value = undefined;
let error = undefined;
let result = this.then(v => {
value = v;
isFulfilled = true;
isPending = false;
return v;
}, e => {
error = e;
isRejected = true;
isPending = false;
throw e;
});
result.isFulfilled = () => isFulfilled;
result.isPending = () => isPending;
result.isRejected = () => isRejected;
result.value = () => value;
result.error = () => error;
return result;
}
/**** Example ******
const apiCall = fetch('/api').getQueryable();
if (apiCall.isPending()) {
console.log('still waiting for request to finish');
} else if (apiCall.isFulfilled()) {
console.log('response', apiCall.value());
} else {
// Must have errorer
console.log('error from fetch', apiCall.error());
}
*****************/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment