yaplib
v0.2.2
Published
yaplib - Yet Another Promise Library for working with promises
Downloads
5
Maintainers
Readme
yaplib - Yet Another Promise Library
Tiny promise utilities for modern JS.
I find myself writing various promise helpers over time and decided to publish them in a package.
Install
npm i yaplibQuick start
Async cleanup (await using)
import { defer } from 'yaplib'
async function run() {
await using _cleanup = defer(async () => {
await db.close()
})
// ...work...
}
await run()Sync cleanup (using)
import { deferSync } from 'yaplib'
function run() {
using _cleanup = deferSync(() => lock.release())
// ...work...
}
run()API
defer(fn): AsyncDisposable
export function defer(fn: () => unknown | PromiseLike<unknown>): AsyncDisposable- Runs
fnwhen the scope exits viaawait using. - Idempotent & coalesced: multiple or concurrent disposals run
fnonce; later calls await the same promise. - Error propagation: if
fnthrows/rejects, disposal rejects with that error.
deferSync(fn): Disposable
export function deferSync(fn: () => unknown): Disposable- Runs
fnwhen the scope exits viausing(synchronous path). - Idempotent: multiple disposals after the first are no-ops.
- For async cleanups, use
deferinstead so callers canawaitcompletion.
Semantics & edge cases
- With
await using, cleanup runs after the last statement in the scope and before the function resolves. - If both the body and the cleanup throw during
await using, some runtimes surface aSuppressedErrorthat preserves both errors. - Double-dispose and overlapping disposals are safe:
deferruns once and shares the same promise;deferSyncruns once.
TypeScript
Add the libs that declare using/await using and disposables:
// tsconfig.json
{
"compilerOptions": {
"lib": "ESNext" // or ["ES2024", "ESNext.Disposable"]
}
}Why not try/finally?
These helpers give the same guarantees with less boilerplate, integrate with using/await using, and coalesce concurrent disposal calls safely.
Roadmap
More small, focused promise utilities will be added over time.
