Created
November 24, 2017 18:25
-
-
Save gabemeola/281917ff3219ad6147a83bf0f48bcf8f to your computer and use it in GitHub Desktop.
Deferred Object using native Promises
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 noop = () => {}; | |
/** | |
* This Class creates a Promise object | |
* that has its resolve and reject | |
* methods publicly exposed. | |
* | |
* This allows a user to resolve / reject | |
* this promise from outside the Promise function scope. | |
*/ | |
export default class Deferred { | |
constructor() { | |
// Private API for telling if | |
// promise is still pending. | |
this._promiseIsResolved = false; | |
this.promise = new Promise((resolve, reject) => { | |
this.reject = reject; | |
this.resolve = resolve; | |
}); | |
this.promise | |
.then(() => { | |
// Set promiseIsResolved to true once resolved. | |
this.promiseIsResolved = true; | |
}) | |
.catch(noop) | |
} | |
/** | |
* Returns promiseIsResolved variable. | |
*/ | |
isResolved() { | |
return this._promiseIsResolved; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment