universal-common
Version:
Library that provides useful missing base class library functionality.
57 lines (56 loc) • 2.17 kB
TypeScript
/**
* 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 {
/**
* 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(): Promise<any>;
/**
* 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: any): void;
/**
* 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: any): void;
#private;
}