universal-common
Version:
Library that provides useful missing base class library functionality.
84 lines (78 loc) • 3.02 kB
JavaScript
/**
* A class that provides external control over a Promise's resolution or rejection.
*
* This pattern is similar to C#'s TaskCompletionSource or Java's CompletableFuture,
* allowing you to create a Promise and control when and how it completes from outside
* the Promise's executor function.
*
* This is useful in scenarios where:
* - Promise resolution must be triggered by external events
* - You need to bridge callback-based APIs to Promise-based code
* - You want to manually control the timing of Promise resolution
*/
export default class PromiseCompletionSource {
// Private fields to store the Promise and its control functions
#promise; // The Promise that can be awaited externally
#resolve; // Function to resolve the Promise with a value
#reject; // Function to reject the Promise with a reason
/**
* Creates a new PromiseCompletionSource instance.
* Initializes an internal Promise that can be controlled externally
* through the resolve and reject methods.
*/
constructor() {
let self = this; // Capture 'this' reference for use in the Promise executor
let promise = new Promise(function (resolve, reject) {
self.#resolve = resolve;
self.#reject = reject;
});
this.#promise = promise;
}
/**
* Gets the Promise controlled by this PromiseCompletionSource.
*
* @returns {Promise} The Promise that will be resolved or rejected when the
* corresponding methods on this PromiseCompletionSource are called.
*
* @example
* const pcs = new PromiseCompletionSource();
* const promise = pcs.promise;
* promise.then(value => console.log('Resolved with:', value));
*/
get promise() {
return this.#promise;
}
/**
* Resolves the Promise with the specified value.
*
* @param {*} value - The value to resolve the Promise with
*
* @example
* const pcs = new PromiseCompletionSource();
* // Later, when a condition is met:
* pcs.resolve('Operation completed');
*
* @note Once a Promise is resolved or rejected, subsequent calls to
* resolve() or reject() will have no effect as per Promise semantics.
*/
resolve(value) {
this.#resolve(value);
}
/**
* Rejects the Promise with the specified reason.
*
* @param {*} value - The reason for rejecting the Promise
* Typically an Error object or error message
*
* @example
* const pcs = new PromiseCompletionSource();
* // Later, if an error occurs:
* pcs.reject(new Error('Operation failed'));
*
* @note Once a Promise is resolved or rejected, subsequent calls to
* resolve() or reject() will have no effect as per Promise semantics.
*/
reject(value) {
this.#reject(value);
}
}