Cancel work
Take an AbortSignal from JavaScript and check it; the promise rejects with an AbortError.
import { delay } from "lucent:core";
export async function search( words: string[], query: string, signal: AbortSignal,): Promise<string[]> { const found: string[] = []; for (let i = 0; i < words.length; i++) { if (i % 1000 === 0) { signal.throwIfAborted(); await delay(0); // let other calls in between chunks } const word = words[i]!; if (word.includes(query)) found.push(word); } return found;}const controller = new AbortController();const results = search(words, "lu", controller.signal);
controller.abort(); // results rejects with an AbortErrorPass an AbortSignal from JavaScript. When JavaScript calls abort(), the signal is set in native code at once. Your code stops where it checks: signal.throwIfAborted(), or a delay(ms, signal).
- The rejection is an
ErrornamedAbortError, or the reason JavaScript passed toabort(). signal.abortedreads the state, andsignal.addEventListener("abort", …)runs a function when it's set.- A signal can come into Lucent, but not go back out, and an
AbortControllercan't cross at all.