A collection of useful TypeScript/JavaScript utilities for crypto, date, string, number, JSON operations and more.
—
Promise timeout handling with custom error types and wrapper functions for time-limited operations, essential for preventing hanging operations in network requests and long-running tasks.
Custom error class for timeout operations with timeout value preservation.
/**
* Custom error class for timeout operations
*/
class TimeoutError extends Error {
timeout: number;
constructor(timeout: number);
}Usage Examples:
import { TimeoutError } from "utility";
// Create timeout error
const error = new TimeoutError(5000);
console.log(error.message); // "Timed out after 5000ms"
console.log(error.timeout); // 5000
console.log(error.name); // "TimeoutError"
// Error handling
try {
throw new TimeoutError(3000);
} catch (err) {
if (err instanceof TimeoutError) {
console.log(`Operation timed out after ${err.timeout}ms`);
}
}Add timeout functionality to any promise with automatic cleanup.
/**
* Add timeout to a promise with automatic cleanup
* @param promiseArg - Promise to add timeout to
* @param timeout - Timeout in milliseconds
* @returns Promise that rejects with TimeoutError if timeout exceeded
*/
function promiseTimeout<T>(promiseArg: Promise<T>, timeout: number): Promise<T>;Usage Examples:
import { promiseTimeout, TimeoutError } from "utility";
// Basic timeout usage
const fetchWithTimeout = promiseTimeout(
fetch('https://api.example.com/data'),
5000
);
try {
const response = await fetchWithTimeout;
const data = await response.json();
} catch (error) {
if (error instanceof TimeoutError) {
console.log('Request timed out after 5 seconds');
}
}
// Database query with timeout
const query = promiseTimeout(
database.query('SELECT * FROM users'),
10000
);
// File operation with timeout
const fileRead = promiseTimeout(
fs.readFile('large-file.txt', 'utf8'),
30000
);
// Chain with other operations
const result = await promiseTimeout(
someAsyncOperation().then(data => processData(data)),
15000
);Wrapper function that creates and times out a promise-returning function.
/**
* Run a promise-returning function with timeout
* @param scope - Function that returns a promise
* @param timeout - Timeout in milliseconds
* @returns Promise that rejects with TimeoutError if timeout exceeded
*/
function runWithTimeout<T>(scope: () => Promise<T>, timeout: number): Promise<T>;Usage Examples:
import { runWithTimeout, TimeoutError } from "utility";
// Simple async operation with timeout
const result = await runWithTimeout(async () => {
const response = await fetch('https://api.example.com/slow-endpoint');
return response.json();
}, 8000);
// Complex operation with timeout
const processedData = await runWithTimeout(async () => {
const data = await fetchLargeDataset();
const processed = await processInBackground(data);
const validated = await validateResults(processed);
return validated;
}, 60000);
// Error handling
try {
const result = await runWithTimeout(async () => {
await new Promise(resolve => setTimeout(resolve, 10000)); // 10 second delay
return 'completed';
}, 5000); // 5 second timeout
} catch (error) {
if (error instanceof TimeoutError) {
console.log('Operation took too long');
}
}
// Retry with timeout
async function retryWithTimeout<T>(
operation: () => Promise<T>,
maxRetries: number = 3,
timeout: number = 5000
): Promise<T> {
for (let i = 0; i < maxRetries; i++) {
try {
return await runWithTimeout(operation, timeout);
} catch (error) {
if (error instanceof TimeoutError && i < maxRetries - 1) {
console.log(`Attempt ${i + 1} timed out, retrying...`);
continue;
}
throw error;
}
}
throw new Error('All retries failed');
}Install with Tessl CLI
npx tessl i tessl/npm-utility