Keep the latest asynchronous task
Keep overlapping searches aligned with the newest input.
Table of contents
APIs used
- mount
- Starts a Valyrian.js application on a DOM target.
- Task
- Coordinates concurrent asynchronous work.
Run this recipe
- Starting project
- Use the local TSX and ESM project from Stage 1 with Valyrian.js installed and its ESM browser build configured.
- File
- Replace src/client-entry.tsx with this recipe snippet.
- Run
- Run npm run build, serve public with npx --yes serve@14.2.5 public --listen 8000, open http://localhost:8000 and use the example's visible controls.
- Observable result
- The rendered result belongs to valyrian.js after the earlier valyrian run also finishes.
Starting point
Create a search Task with the takeLatest strategy and read its running, success, error or cancelled state.
Steps
Call run(args) twice with self-contained delayed search results. The first run finishes later, while the second becomes the active result.
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 rendered result belongs to valyrian.js after the earlier valyrian run also finishes.
Limits
takeLatest keeps stale completion from replacing current state. restartable is the strategy that models replacing work through cancellation.