Skip to content

Utility class to wrap classes that are meant for method chaining, specifically useful for functions that return Promises. Promise functions and non-promise functions can be mixed.

License

Notifications You must be signed in to change notification settings

myty/promise-chain

Repository files navigation

PromiseChain

JSR JSR Score GitHub version deno land npm version Coverage Status

Wrapper utility class that enables composition via asynchronous (Promises) and synchronous method chaining.

Installation

Node.js

# npm
npm install --save promise-chain
# yarn
yarn add promise-chain
# pnpm
pnpm install --save promise-chain

Deno

import Composable from "https://deno.land/x/promise_chain/mod.ts";

Example Usage

Provided the following class:

class TestClass {
  public readonly propertyOne: number;
  public readonly propertyTwo: number;

  constructor({
    propertyOne = 0,
    propertyTwo = 0,
  }: Partial<TestClass> = {}) {
    this.propertyOne = propertyOne;
    this.propertyTwo = propertyTwo;
  }

  async asyncIncrement(
    property: string,
    increment: number,
  ): Promise<TestClass> {
    return new TestClass({
      ...this,
      [property]: await Promise.resolve(this[property] + increment),
    });
  }

  increment(
    property: string,
    increment: number,
  ): Promise<TestClass> {
    return new TestClass({
      ...this,
      [property]: this[property] + increment,
    });
  }
}

Traditionally to chain these methods you would need to do the follwing:

const { propertyOne, propertyTwo } = await testClass
  .asyncIncrement("propertyOne", 3)
  .then((t) => t.asyncIncrement("propertyTwo", 5))
  .then((t) => Promise.resolve(t.increment("propertyTwo", 5)));

console.log(`Result: propertyOne=${propertyOne}, propertyTwo=${propertyTwo}`);
// OUTPUT: "Result: propertyOne=3, propertyTwo=10"

With PromiseChain, it is simplified and easier to read.

const { propertyOne, propertyTwo } = await PromiseChain(testClass)
  .asyncIncrement("propertyOne", 3)
  .asyncIncrement("propertyTwo", 5)
  .increment("propertyTwo", 5);

console.log(`Result: propertyOne=${propertyOne}, propertyTwo=${propertyTwo}`);
// OUTPUT: "Result: propertyOne=3, propertyTwo=10"

About

Utility class to wrap classes that are meant for method chaining, specifically useful for functions that return Promises. Promise functions and non-promise functions can be mixed.

Topics

Resources

License

Stars

Watchers

Forks