API reference › @evolu/common › Callbacks › Callbacks
Defined in: packages/common/src/Callbacks.ts:66
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.
Correlating callback responses
import { assertEqual, createCallbacks, testCreateDeps } from "@evolu/common";
const deps = testCreateDeps();
// No-argument callback
using callbacks = createCallbacks(deps);
let noArgumentCalls = 0;
const noArgumentId = callbacks.register(() => {
noArgumentCalls++;
});
callbacks.execute(noArgumentId);
callbacks.execute(noArgumentId);
assertEqual(noArgumentCalls, 1);
// Typed callback
using stringCallbacks = createCallbacks<string>(deps);
let received = "";
const stringCallbackId = stringCallbacks.register((value) => {
received = value;
});
stringCallbacks.execute(stringCallbackId, "hello");
assertEqual(received, "hello");
// Promise.withResolvers
using promiseCallbacks = createCallbacks<string>(deps);
const { promise, resolve } = Promise.withResolvers<string>();
const promiseCallbackId = promiseCallbacks.register(resolve);
promiseCallbacks.execute(promiseCallbackId, "resolved value");
assertEqual(await promise, "resolved value");
Extends
Methods
[dispose]()
dispose: void;
Defined in: node_modules/@typescript/old/lib/lib.esnext.disposable.d.ts:34
Inherited from
Disposable.[dispose]
Properties
execute
readonly execute: T extends undefined ? (id: string & Brand<"Id">) => undefined : (id: string & Brand<"Id">, arg: T) => undefined;
Defined in: packages/common/src/Callbacks.ts:71
Executes and removes a callback associated with the given ID.
register
readonly register: (callback: Callback<T>) => string & Brand<"Id">;
Defined in: packages/common/src/Callbacks.ts:68
Registers a callback function and returns a unique ID.