Skip to content

Class BackgroundRunner

Source: BackgroundRunner.ts

Runs async callbacks "fire-and-forget" style in the background. The calling fiber does not await the callback's Promise, so it continues running without blocking.

Any errors thrown or rejections from background callbacks are automatically caught and emitted as 'error' events. This prevents unhandled promise rejections.

Import

ts
import { BackgroundRunner } from '@litert/utils-async';

Constructor

ts
new BackgroundRunner(opts?: IBackgroundRunnerOptions)

Parameters

Events

EventArgumentsDescription
'error'(error: unknown)Emitted when a background callback throws or rejects.

Methods

run

ts
run(callback: () => Promise<void>): void;

Starts callback immediately in the background. The callback's Promise is not awaited. If the callback throws synchronously or rejects, the error is emitted as an 'error' event.

runLater

ts
runLater(callback: () => Promise<void>, wait?: () => Promise<void>): void;

Schedules callback to run after the wait function resolves. By default, wait is DEFAULT_BG_RUNNER_WAIT_FN (sleep(0) — next event loop tick).

Parameters

  • callback — The async callback to run in the background.
  • wait? — Override the wait function for this specific invocation.

Examples

ts
import { BackgroundRunner } from '@litert/utils-async';

const runner = new BackgroundRunner();

runner.on('error', (err) => {
    console.error('Background task failed:', err);
});

// Fire-and-forget: don't wait for the result
runner.run(async () => {
    await sendAnalyticsEvent({ type: 'pageview' });
});

// Deferred: run on next tick
runner.runLater(async () => {
    await cleanUpTempFiles();
});