Skip to main content
Module

x/effection/mod.ts>Task

Structured concurrency and effects for JavaScript
Latest
interface Task
implements Future<T>
Re-export
import { type Task } from "https://deno.land/x/effection@3.0.3/mod.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

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

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

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

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);
});

Methods

halt(): Future<void>

Interrupt and shut down a running Operation and all of its children.

Any errors raised by the halt() operation only represent problems that occured during the teardown of the task. In other words, halt() can succeed even if the task failed.