Effection Logo
@effectionx/chainv0.1.0thefrontside/effectionx
JSR BadgeNPM Badge with published version
import { } from "@effectionx/chain"

Chain

There are some use-cases for Promise for which there is not a 1:1 analogue in Effection. One of these is the "promise chaining" behavior of the Promise constructor itself using then(), catch(), and finally().

The chain package accomplishes this in a very similar way:

import { Chain } from "@effectionx/chain";

await main(function* () {
  let chain = new Chain<number>((resolve) => {
    resolve(10);
  });

  let result = yield* chain.then(function* (value) {
    return value * 2;
  });

  console.log(result); //=> 20;
});

Another is to share a promise in multiple places. For example this async data call is used and re-used:

class Foo {
  data: Promise<number>;

  constructor() {
    this.data = (async () => 5)();
  }

  async getData() {
    return await this.data;
  }
}

const foo = new Foo();
console.log(await foo.getData());

This can be accomplished with Chain like so:

class Foo {
  data: Promise<number>;

  constructor() {
    let operation = (function* () {
      return 5;
    })();
    this.data = Chain.from(operation);
  }

  *getData() {
    return yield* this.data;
  }
}

const foo = new Foo();
console.log(yield * foo.getData());

import { Chain } from "@effectionx/chain";

await main(function* () {
  let chain = new Chain<number>((resolve) => {
    resolve(10);
  });

  let result = yield* chain.then(function* (value) {
    return value * 2;
  });

  console.log(result); //=> 20;
});

API Reference

type Resolve = WithResolvers<T>["resolve"]

Resolve a Chain

Type Parameters

T

type Reject = WithResolvers<unknown>["reject"]

Reject a chain

class Chain implements From<T>

Represent the eventual completion of an [Operation] in a fashion that mirrors the * https implementation

Constructors

new Chain(compute: (resolve: Resolve<T>, reject: Reject) => void)

Methods

then<B>(fn: (value: T) => Operation<B>): From<B>

No documentation available.

catch<B>(fn: (error: unknown | Error) => Operation<B>): From<T | B>

No documentation available.

finally(fn: () => Operation<void>): From<T>

No documentation available.

[Symbol.iterator](): ReturnType<From<T>[]>

No documentation available.

interface From<A> extends Operation<A>