UNPKG

@kitiumai/utils-ts

Version:

Comprehensive TypeScript utilities for KitiumAI projects

132 lines 3.31 kB
/** * Async/Promise utility functions */ /** * Sleep for specified milliseconds */ export function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } /** * Retry async function with exponential backoff */ export async function retry(fn, options = {}) { const { retries = 3, delay = 1000, backoff = 2, onRetry } = options; let lastError; for (let attempt = 0; attempt <= retries; attempt++) { try { return await fn(); } catch (error) { lastError = error; if (attempt < retries) { const waitTime = delay * Math.pow(backoff, attempt); onRetry?.(lastError, attempt + 1); await sleep(waitTime); } } } throw lastError; } /** * Add timeout to promise */ export function timeout(promise, ms, message = 'Operation timed out') { return Promise.race([ promise, new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms)), ]); } /** * Run promises in parallel */ export async function parallel(fns) { return Promise.all(fns.map((fn) => fn())); } /** * Run promises in series (one after another) */ export async function series(fns) { const results = []; for (const fn of fns) { results.push(await fn()); } return results; } /** * Run async function with concurrency limit */ export async function concurrency(items, fn, limit) { const results = new Array(items.length); const executing = []; for (let i = 0; i < items.length; i++) { const item = items[i]; if (item === undefined) { continue; } const promise = fn(item).then((result) => { results[i] = result; }); executing.push(promise); if (executing.length >= limit) { await Promise.race(executing); const index = executing.findIndex((p) => p === promise); if (index !== -1) { executing.splice(index, 1); } } } await Promise.all(executing); return results; } /** * Promisify callback-based function */ export function promisify(fn) { return (...args) => { return new Promise((resolve, reject) => { fn(...args, (error, result) => { if (error) { reject(error); } else { resolve(result); } }); }); }; } /** * Wrap promise to never reject */ export async function settled(promise) { try { const value = await promise; return { success: true, value }; } catch (error) { return { success: false, error: error }; } } /** * Race promises, return first to complete (success or failure) */ export function race(promises) { return Promise.race(promises); } /** * Wait for all promises to settle (fulfilled or rejected) */ export function allSettled(promises) { return Promise.allSettled(promises); } export function deferred() { let resolve; let reject; const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); return { promise, resolve, reject }; } //# sourceMappingURL=async.js.map