@myty/promise-chain
TypeScript icon, indicating that this package has built-in type declarations

0.4.6 • Public • Published

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"

Readme

Keywords

none

Package Sidebar

Install

npm i @myty/promise-chain

Weekly Downloads

7

Version

0.4.6

License

MIT

Unpacked Size

11.3 kB

Total Files

17

Last publish

Collaborators

  • myty