API reference › @evolu/common › Callbacks › Callbacks
Defined in: packages/common/src/Callbacks.ts:51
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"
Extends
Methods
[dispose]()
dispose: void;
Defined in: node_modules/.bun/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.disposable.d.ts:36
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:56
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:53
Registers a callback function and returns a unique ID.