UNPKG

@naturalcycles/js-lib

Version:

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

52 lines (51 loc) 2.01 kB
import type { CommonLogger } from './log/commonLogger.js'; import type { NumberOfMilliseconds } from './types.js'; declare class AsyncManagerImpl { logger: CommonLogger; pendingOps: Set<Promise<unknown>>; private onErrorHooks; runInBackground(promise: Promise<unknown>): void; onError(fn: OnErrorHook): void; /** * Resolves when all pending operations settle. * They may resolve or reject, allDone will never throw. * Errors (rejections) are reported to onErrorHooks (instead). * * If timeout is specified - it resolves if timeout has reached. */ allDone(timeout?: NumberOfMilliseconds): Promise<void>; reset(): void; private fireOnErrorHooks; } /** * Singleton which keeps track of async operations - "voided promise-returning functions" * that should run in parallel to the main request. * * It is an alternative to do `void doSomeAnalytics()`, which should run in parallel * and not block the request (not slow down nor fail the request on analytics api failure). * * At the same time, `void doSomeAnalytics()` gets completely detached and untracked, * nothing awaits it, its rejection becomes unhandledRejection (and may kill Node.js process). * * With AsyncManager, you instead register all those "voided" calls like this: * * AsyncManager.runInBackground(doSomeAnalytics()) * * Then, in a few places you may be interested to ensure that all async operations have been finished. * The places can be: * - Graceful shutdown of a backend service * - Before the end of runScript * - At the end of each unit test, to make sure async ops don't leak * * You ensure no pending async operations like this: * * await AsyncManager.allDone() * * which never throws, but instead awaits all operations to be settled. * * @experimental */ export declare const AsyncManager: AsyncManagerImpl; export declare const runInBackground: (promise: Promise<unknown>) => void; export type OnErrorHook = (err: Error) => any; export {};