Effection Logo

function action

thefrontside/effection

function action<T>(operation: (resolve: Resolve<T>, reject: Reject) => Operation<void>): Operation<T>

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

Type Parameters

T

  • type of the action's result.

Parameters

operation: (resolve: Resolve<T>, reject: Reject) => Operation<void>

  • body of the action

Return Type

Operation<T>

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