Created
August 21, 2023 15:16
-
-
Save goodevilgenius/b7d90010763fc5244b0c9b71b44b1ee5 to your computer and use it in GitHub Desktop.
A javascript promise that can tell you if it's been fulfilled.
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
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