Skip to content
Lucent
SEARCH LUCENT

Search guides, APIs, and examples.

GitHub

Very early and experimental. The language, the generated native code and every package API change without notice. Do not use Lucent in production.

Accept a JS callback

A function parameter: called at once during a synchronous call, posted to the JS thread from async code.

callbacks.lucent.ts
/** Synchronous: the callback runs while JavaScript waits, and may return a value. */
export function sortBy(words: string[], key: (word: string) => number): string[] {
return [...words].sort((a, b) => key(a) - key(b));
}
/** From async code: the callback is posted to the JS thread, so it returns void. */
export async function countTo(n: number, onStep: (step: number) => void): Promise<void> {
for (let i = 1; i <= n; i++) onStep(i);
}
/** Returning a Promise lets async code wait for JavaScript's answer. */
export async function askTwice(ask: (question: string) => Promise<number>): Promise<number> {
const a = await ask("first");
const b = await ask("second");
return a + b;
}
Called fromThe callbackIt may return
a synchronous exportruns at once, on the JS threadany value that can cross; it's checked
async codeis posted to the JS threadvoid, or a Promise that Lucent can await
  • A callback that throws, or whose promise rejects, throws in Lucent too: catch it there.
  • Lucent keeps a callback while it holds a reference to it, and releases it on the JS thread after.
  • After a reload, a stale void callback does nothing; one that returns a value throws.