UNPKG

@naturalcycles/js-lib

Version:

Standard library for universal (browser + Node.js) javascript

38 lines (37 loc) 1.07 kB
import { pDefer } from './pDefer.js'; /** * Promisified version of setTimeout. * * Can return a value. * If value is instanceof Error - rejects the Promise instead of resolving. */ export async function pDelay(ms = 0, value) { return await new Promise((resolve, reject) => setTimeout(value instanceof Error ? reject : resolve, ms, value)); } /* oxlint-disable @typescript-eslint/promise-function-async */ /** * Promisified version of setTimeout. * * Wraps the passed function with try/catch, * catch will propagate to pDelayFn rejection, * otherwise pDelayFn will resolve with returned value. * * On abort() - clears the Timeout and immediately resolves the Promise with void. */ export function pDelayFn(ms, fn) { const p = pDefer(); const timer = setTimeout(async () => { try { p.resolve(await fn()); } catch (err) { p.reject(err); } }, ms); p.abort = () => { clearTimeout(timer); // p.rejectAborted(reason) // nope p.resolve(); }; return p; }