@bemedev/better-promise
Promise utilities with timeout control, race helpers, and strong typing.
Installation
pnpm add @bemedev/better-promise
API
withTimeout(promise, id, ...timeouts)
Wraps a promise with one or more timeout deadlines. Rejects with a message
like "Timed out after 500 ms." if the promise does not settle in time.
Automatically clears all timers on settlement.
import { withTimeout } from '@bemedev/better-promise';
const wrapped = withTimeout(
() => fetch('/api/data').then(r => r.json()),
'fetch-data',
3000, // reject after 3 s
);
const result = await wrapped();
// Cancel at any time
wrapped.abort();
withTimeout.safe(promise, id, ...timeouts)
Same as withTimeout but resolves to undefined instead of rejecting on
timeout or abort.
racePromises(id, ...promises)
Races multiple TimeoutPromises using Promise.race. The first to settle
wins; all others are aborted.
import { racePromises, withTimeout } from '@bemedev/better-promise';
const a = withTimeout(() => fetchA(), 'a', 1000);
const b = withTimeout(() => fetchB(), 'b', 1000);
const winner = racePromises('race-ab', a, b);
const result = await winner();
anyPromises(id, ...promises)
Races multiple TimeoutPromises using Promise.any. Resolves with the
first fulfillment; rejects only when all have rejected.
import { anyPromises, withTimeout } from '@bemedev/better-promise';
const a = withTimeout(() => fetchA(), 'a', 1000);
const b = withTimeout(() => fetchB(), 'b', 1000);
const first = anyPromises('any-ab', a, b);
const result = await first();
asyncfy(fn)
Wraps a synchronous function so it returns a Promise.
import { asyncfy } from '@bemedev/better-promise';
const asyncAdd = asyncfy((a: number, b: number) => a + b);
const result = await asyncAdd(1, 2); // 3
typedPromisify(fn)
Converts a Node.js-style callback function (…args, cb) into a
promise-returning function, fully typed.
import { typedPromisify } from '@bemedev/better-promise';
import fs from 'node:fs';
const readFile = typedPromisify(fs.readFile);
const content = await readFile('./file.txt', 'utf8');
Types
| Type | Description |
|---|---|
TimeoutPromise<T> |
Callable promise with .abort() and .id properties |
TypeFromTimeout<T> |
Extracts the resolved type from a TimeoutPromise<T> |
TypeFromTimeouts<T> |
Extracts the union of resolved types from TimeoutPromise[] |
Fn<Args, R> |
Generic function type |
FnBasic<Main, Tr> |
Intersection of a function type and an object type |
Callback |
Node-style callback — (err, result?) or (err) |
CallBackError |
Callback with error only — (err: any) => void |
CallBackResult<T> |
Callback with error and result — (err: any, result: T) |
CbParams |
Tuple of [...args, Callback] |
ResultFrom<T> |
Infers the promise-returning signature from CbParams |
Licence
MIT
CHANGELOG
Read CHANGELOG.md for more details about the changes.
Auteur
chlbri (bri_lvi@icloud.com)