Coordinate replaceable asynchronous work
Keep overlapping searches aligned with the newest user input.
The self-contained example starts two delayed searches and renders the result retained by the latest run after the earlier work finishes.
Table of contents
Main APIs
- Task
- Coordinates concurrent asynchronous work.
tsimport { mount } from "valyrian.js";
import { Task } from "valyrian.js/tasks";
const searchTask = new Task(
async (query: string) => {
const delay = query === "valyrian" ? 20 : 5;
await new Promise((resolve) => setTimeout(resolve, delay));
return [`${query} guide`, `${query} reference`];
},
{ strategy: "takeLatest" },
);
const superseded = searchTask.run("valyrian");
const result = await searchTask.run("valyrian.js");
await superseded;
mount(
"body",
() => `status: ${searchTask.state.status}; result: ${JSON.stringify(result)}`,
);Result
The second search remains current when the first one finishes later.