import { type Task } from "https://deno.land/x/effection@4.0.0-alpha.1/lib/types.ts";
A handle to a concurrently running operation that lets you either use the result of that operation, or shut it down.
When it is run or spawned, an operation executes concurrently with
the rest of the program. The Task
is both an Operation and a
Promise
that lets you consume the result of that operation.
Examples
Example 1
Example 1
import { run, sleep } from "effection";
let task = run(function*() {
yield* sleep(100);
return "hello world"
});
console.log(await task); //=> "hello world"
A task can also be created from within an operation by using the spawn() operation.
Example 2
Example 2
import { run, spawn, sleep } from "effection";
await run(function*() {
let task = yield* spawn(function*() {
yield* sleep(100);
return "hello world";
});
console.log(yield* task;) //=> "hello world"
});
Note tasks are subject to the strict guarantees of structured concurrency and will never outlive their parent. For example, the following spawned task will never log any output to the console.
Example 3
Example 3
import { run, spawn, sleep } from "effection";
await run(function*() {
yield* spawn(function*() {
yield* sleep(100);
console.log("hello world");
});
// <--- returns here, so spawned task is shut down as it sleeps.
});
See the guide on Scopes for more detail.
If a Task
is halted before it finishes executing, then consuming it's
result is an Error.
Example 4
Example 4
import { run, spawn, sleep } from "effection";
await run(function*() {
let task = yield* spawn(function*() {
yield* sleep(100);
return "hello world";
});
yield* task.halt();
let output = yield* task; //=> throws Error("halted");
console.log(output);
});