Skip to content

Instantly share code, notes, and snippets.

@nyteshade
Created October 26, 2022 18:47
Show Gist options
  • Save nyteshade/69ab168a97f8f31ec3eea9aa5cb8bf79 to your computer and use it in GitHub Desktop.
Save nyteshade/69ab168a97f8f31ec3eea9aa5cb8bf79 to your computer and use it in GitHub Desktop.
Deferred Promises, a useful tidbit that jQuery devised
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);
}
@nyteshade
Copy link
Author

Also as a one liner

const Deferred = () => { let o = {}; o.promise = new Promise((resolve, reject) => Object.assign(o, { resolve, reject })); return o; }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment