Skip to content

Instantly share code, notes, and snippets.

@gabemeola
Created November 24, 2017 18:25
Show Gist options
  • Save gabemeola/281917ff3219ad6147a83bf0f48bcf8f to your computer and use it in GitHub Desktop.
Save gabemeola/281917ff3219ad6147a83bf0f48bcf8f to your computer and use it in GitHub Desktop.
Deferred Object using native Promises
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