1.0.0 • Published 5 months ago

@silyze/resolver v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
5 months ago

@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/resolver

Usage

import createResolver from "@silyze/resolver";

const { promise, resolve, reject } = createResolver<number>();

setTimeout(() => resolve(42), 1000);

const result = await promise; // 42

API

createResolver<T>(): ResolverWithPromise<T>

Returns an object with the following properties:

PropertyTypeDescription
promisePromise<T>The promise that can be awaited or chained
resolve`(value: TPromiseLike) => void`Resolves the promise
reject(error: Error) => voidRejects 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

EnvironmentNative SupportWorks with @silyze/resolver
Node.js 22+YesYes (uses native)
Node.js 14–21NoYes (uses polyfill)
Modern BrowsersYesYes
Older BrowsersNoYes

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