1.0.0 • Published 5 months ago
@silyze/resolver v1.0.0
@silyze/resolver
A minimal wrapper around Promise.withResolvers() with a built-in polyfill for environments that do not yet support the native API.
This utility allows you to obtain a promise, resolve, and reject object in a clean and consistent way.
Features
- Uses native
Promise.withResolvers()when available (Node 22+, modern browsers) - Falls back to a spec-compliant polyfill when not available
- Type-safe with full TypeScript support
- Lightweight and dependency-free
- Supports both CommonJS and ES Modules
Installation
npm install @silyze/resolverUsage
import createResolver from "@silyze/resolver";
const { promise, resolve, reject } = createResolver<number>();
setTimeout(() => resolve(42), 1000);
const result = await promise; // 42API
createResolver<T>(): ResolverWithPromise<T>
Returns an object with the following properties:
| Property | Type | Description | |
|---|---|---|---|
promise | Promise<T> | The promise that can be awaited or chained | |
resolve | `(value: T | PromiseLike) => void` | Resolves the promise |
reject | (error: Error) => void | Rejects the promise |
Example
const { promise, resolve, reject } = createResolver<string>();
someStream.on("data", resolve);
someStream.on("error", reject);
try {
const data = await promise;
console.log("Received:", data);
} catch (err) {
console.error("Stream failed:", err);
}Polyfill Behavior
If Promise.withResolvers() is not available, this package will fall back to an internal implementation using new Promise().
Compatibility
| Environment | Native Support | Works with @silyze/resolver |
|---|---|---|
| Node.js 22+ | Yes | Yes (uses native) |
| Node.js 14–21 | No | Yes (uses polyfill) |
| Modern Browsers | Yes | Yes |
| Older Browsers | No | Yes |
Type Definitions
export type Resolver<T> = {
resolve: (value: T | PromiseLike<T>) => void;
reject: (error: Error) => void;
};
export type ResolverWithPromise<T> = Resolver<T> & {
promise: Promise<T>;
};1.0.0
5 months ago