high-performance JavaScript utility library with a small bundle size and strong type annotations.
- 🚀 High Performance: optimized for performance.
- 📦 Small Bundle Size: small bundle size.
- 🎯 Strong Type Annotations: written in TypeScript with full types support.
npm install @esmkit/promise
bun add @esmkit/promise
Delays the execution of code for a specified number of milliseconds.
This function returns a Promise that resolves after the specified delay, allowing you to use it with async/await to pause execution. It also supports an optional AbortSignal to cancel the delay.
function delay(ms: number, options?: DelayOptions): Promise<void>;
ms
(number
): The number of milliseconds to delay.options
(DelayOptions
, optional): An options object.signal
(AbortSignal
, optional): An optionalAbortSignal
to cancel the delay.
(Promise<void>
): A Promise that resolves after the specified delay.
import { delay } from '@esmkit/promise';
async function foo() {
console.log('Start');
await delay(1000); // Delays execution for 1 second
console.log('End');
}
foo();
import { delay } from '@esmkit/promise';
async function foo() {
const controller = new AbortController();
const signal = controller.signal;
setTimeout(() => controller.abort(), 50); // Will cancel the delay after 50ms
try {
await delay(1000, { signal });
} catch (error) {
console.log(error); // Will log 'The operation was aborted'
}
}
Returns a Promise
that rejects with a TimeoutError
after the specified timeout.
function timeout(ms: number): Promise<never>;
ms
(number
): The number of milliseconds for the promise to reject withTimeoutError
.
(Promise<never>
): A Promise that rejects after the specified timeout.
import { timeout } from '@esmkit/promise';
try {
await timeout(1000); // Timeout exception after 1 second
} catch (error) {
console.error(error); // Will log 'The operation was timed out'
}
Executes an async function and enforces a timeout.
If the promise does not resolve within the specified time, the timeout will trigger and the returned promise will be rejected.
function withTimeout<T>(run: () => Promise<T>, ms: number): Promise<T>;
run
(() => Promise<T>
): A function that returns a promise to be executed.ms
(number
): The timeout duration in milliseconds.
(Promise<T>
): A promise that resolves with the result of the run
function or rejects if the timeout is reached.
import { withTimeout } from '@esmkit/promise';
async function fetchData() {
const response = await fetch('https://example.com/data');
return response.json();
}
try {
const data = await withTimeout(fetchData, 1000);
console.log(data); // Logs the fetched data if `fetchData` is resolved within 1 second.
} catch (error) {
console.error(error); // Will log 'TimeoutError' if `fetchData` is not resolved within 1 second.
}
MIT © BILLGO.ME & Viva Republica, Inc