Created
September 30, 2019 23:40
-
-
Save aada/5d9a11bccc7971aa913d9444edbd0760 to your computer and use it in GitHub Desktop.
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
| const delay = ms => { | |
| return new Promise(res => { | |
| setTimeout(res, ms); | |
| }); | |
| }; | |
| const run = () => { | |
| const promise = MakeQuerablePromise(delay(1000)); | |
| console.log(promise.isPending()); | |
| }; | |
| run(); | |
| function MakeQuerablePromise(promise) { | |
| // Don't modify any promise that has been already modified. | |
| if (promise.isResolved) return promise; | |
| // Set initial state | |
| var isPending = true; | |
| var isRejected = false; | |
| var isFulfilled = false; | |
| // Observe the promise, saving the fulfillment in a closure scope. | |
| var result = promise.then( | |
| function(v) { | |
| isFulfilled = true; | |
| isPending = false; | |
| return v; | |
| }, | |
| function(e) { | |
| isRejected = true; | |
| isPending = false; | |
| throw e; | |
| } | |
| ); | |
| result.isFulfilled = function() { | |
| return isFulfilled; | |
| }; | |
| result.isPending = function() { | |
| return isPending; | |
| }; | |
| result.isRejected = function() { | |
| return isRejected; | |
| }; | |
| return result; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment