tiny-future
Version:
A zero-dependency Future/Promise wrapper to resolve or reject a Promise outside its executor.
68 lines (64 loc) • 1.74 kB
JavaScript
;
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
class Future {
/**
* Resolves the Promise created by the Future.
*
* @param value - The value to resolve the Promise with, or a Promise that resolves to the value.
*
* @example
* ```ts
* const future = new Future<string>();
* future.resolve('success');
* // or with a Promise
* future.resolve(Promise.resolve('success'));
* ```
*/
resolve;
/**
* Rejects the Promise created by the Future.
*
* @param reason - The reason for rejecting the Promise. Typically an Error object.
*
* @example
* ```ts
* const future = new Future<string>();
* future.reject(new Error('something went wrong'));
* ```
*/
reject;
/**
* The Promise instance created by the Future.
*
* Use this to await the result or attach `.then()` / `.catch()` handlers.
*
* @example
* ```ts
* const future = new Future<number>();
* future.promise.then(value => console.log(value));
* future.resolve(42); // logs: 42
* ```
*/
promise;
/**
* Creates a new Future instance.
*
* Uses `Promise.withResolvers()` if available (ES2024+), otherwise falls back to manual implementation
* for compatibility with older environments.
*/
constructor() {
if (typeof Promise.withResolvers === "function") {
const { promise, resolve, reject } = Promise.withResolvers();
this.promise = promise;
this.resolve = resolve;
this.reject = reject;
} else {
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
}
}
exports.Future = Future;
//# sourceMappingURL=main.cjs.map