waitfor.js
v1.0.1
Published
Utility for controlling how long async operations are awaited.
Downloads
238
Maintainers
Readme
waitfor.js
A minimal utility for controlling how long async operations are awaited.
No dependencies. ESM only.
Installation
npm install waitfor.jsBasic Usage
import waitFor from "waitfor.js";
// Resolves if the fetch completes within 3 seconds, otherwise throws.
const data = await waitFor(fetch("https://api.example.com/data"), 3000);You can also pass an async function instead of a Promise:
const data = await waitFor(() => fetch("https://api.example.com/data"), 3000);API
waitFor(promiseOrFunction, timeoutMs, options?)
| Parameter | Type | Required | Description |
|---------------------|-----------------------------------|----------|------------------------------------------------|
| promiseOrFunction | Promise or () => Promise | Yes | The operation to race against the timeout. |
| timeoutMs | number | Yes | Max milliseconds to wait. <= 0 = immediate. |
| options | object | No | See below. |
Returns: Promise<T> — resolves with the operation's result, or rejects.
Options
| Option | Type | Description |
|------------|---------------|-----------------------------------------------------------------------------|
| message | string | Custom message for the WaitForTimeoutError. |
| fallback | any | If set, a timeout resolves with this value instead of throwing. |
| signal | AbortSignal | Abort the wait early. Rejects immediately if already aborted on entry. |
Examples
Custom timeout message
const result = await waitFor(slowOperation(), 5000, {
message: "slowOperation took too long",
});Fallback value on timeout
const result = await waitFor(fetchConfig(), 2000, {
fallback: defaultConfig,
});
// result is defaultConfig if fetchConfig() doesn't finish in timeAbortSignal
const controller = new AbortController();
setTimeout(() => controller.abort(), 1000);
try {
const result = await waitFor(longRunningTask(), 10000, {
signal: controller.signal,
});
} catch (err) {
if (err.name === "AbortError") {
console.log("Aborted early.");
}
}Detecting a timeout error
import waitFor, { WaitForTimeoutError } from "waitfor.js";
try {
await waitFor(slowTask(), 3000);
} catch (err) {
if (err instanceof WaitForTimeoutError) {
console.log(`Timed out after ${err.timeoutMs}ms`);
}
}WaitForTimeoutError
Thrown (or passed to .catch) when the timeout elapses without a fallback.
err.name // "WaitForTimeoutError"
err.message // "Operation timed out after 3000ms" (or custom message)
err.timeoutMs // 3000Notes
- Synchronous throws from function inputs are caught and forwarded as rejections.
- Non-Promise return values are wrapped with
Promise.resolve. - Timers and abort listeners are always cleaned up — no leaks on early resolution.
timeoutMs <= 0schedules an immediate timeout (next tick).
License
MIT
