Skip to main content
Module

x/effection/mod.ts>action

Structured concurrency and effects for JavaScript
Latest
function action
Re-export
import { action } from "https://deno.land/x/effection@3.0.3/mod.ts";

Create an Operation that can be either resolved (or rejected) with a synchronous callback. This is the Effection equivalent of new Promise().

The action body is itself an operation that runs in a new scope that is destroyed completely before program execution returns to the point where the action was yielded to.

For example:

let five = yield* action(function*(resolve, reject) {
  setTimeout(() => {
    if (Math.random() > 5) {
      resolve(5)
    } else {
      reject(new Error("bad luck!"));
    }
  }, 1000);
});

However, it is customary to explicitly suspend inside the body of the action so that whenever the action resolves, appropriate cleanup code can run. The preceeding example would be more correctly written as:

let five = yield* action(function*(resolve) {
  let timeoutId = setTimeout(() => {
    if (Math.random() > 5) {
      resolve(5)
    } else {
      reject(new Error("bad luck!"));
    }
  }, 1000);
  try {
    yield* suspend();
  } finally {
    clearTimout(timeoutId);
  }
});

Parameters

operation: (resolve: Resolve<T>, reject: Reject) => Operation<void>
  • body of the action

Returns

an operation producing the resolved value, or throwing the rejected error