API reference / @evolu/common / Callbacks / Callbacks

Interface: Callbacks<T>

Defined in: packages/common/src/Callbacks.ts:45

Request-response correlation for callbacks across boundaries.

Stores callbacks with unique IDs and executes them once with an optional argument. Executed callbacks are automatically removed.

This is useful for correlating asynchronous request-response operations across boundaries where callback functions cannot be passed directly (e.g., web workers, message queues).

The execute method intentionally does not use try-catch or Result because it's the callback's responsibility to handle its own errors.

Example

// No-argument callbacks
const callbacks = createCallbacks(deps);
const id = callbacks.register(() => console.log("called"));
callbacks.execute(id);

// With argument callbacks
const stringCallbacks = createCallbacks<string>(deps);
const id = stringCallbacks.register((value) => {
  console.log(value);
});
stringCallbacks.execute(id, "hello");

// Promise.withResolvers pattern
const promiseCallbacks = createCallbacks<string>(deps);
const { promise, resolve } = Promise.withResolvers<string>();
const id = promiseCallbacks.register(resolve);
promiseCallbacks.execute(id, "resolved value");
await promise; // "resolved value"

Type Parameters

Type ParameterDefault typeDescription
TundefinedThe type of argument passed to callbacks (defaults to undefined for no-argument callbacks)

Properties

PropertyModifierTypeDescriptionDefined in
executereadonlyT extends undefined ? (id) => undefined : (id, arg) => undefinedExecutes and removes a callback associated with the given ID.packages/common/src/Callbacks.ts:50
registerreadonly(callback) => CallbackIdRegisters a callback function and returns a unique ID.packages/common/src/Callbacks.ts:47

Was this page helpful?