Created
October 26, 2022 18:47
-
-
Save nyteshade/69ab168a97f8f31ec3eea9aa5cb8bf79 to your computer and use it in GitHub Desktop.
Deferred Promises, a useful tidbit that jQuery devised
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
export class DeferredPromise { | |
// A definition of this.resolve. If null, this object is uninitialized | |
resolve = null; | |
// A definition of this.reject. If null, this object is uninitialized | |
reject = null; | |
// A definition of this.promise. If null, this object is uninitialized | |
promise = null; | |
// Creates a new instance of DeferredPromise, optionally auto resolving | |
// or rejecting a value. If both are supplied, a truthy autoResolve value | |
// will be resolved and otherwise the autoReject value will be reject()'ed | |
// | |
// @param {any} autoResolveValue a value to automatically resolve | |
// @param {any} autoRejectedValue a value to automatically reject | |
constructor(autoResolvedValue, autoRejectedValue) { | |
this.promise = new Promise((resolve, reject) => { | |
Object.assign(this, { resolve, reject }); | |
if (autoResolvedValue) { | |
resolve(autoResolvedValue); | |
} | |
else if (autoRejectedValue) { | |
reject(autoRejectedValue); | |
} | |
}); | |
} | |
// Ensures any usage of this instance in Object.toString.prototype will produce | |
// a string indicating "[object DeferredPromise]" for ease of identification | |
get [Symbol.toStringTag]() { return this.constructor.name } | |
} | |
export function applySideEffects() { | |
Promise.prototype.deferred = function() { | |
return new DeferredPromise(...arguments); | |
} | |
} | |
export function Deferred() { | |
return new DeferredPromise(...arguments); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also as a one liner