Giter Site home page Giter Site logo

class-states's Introduction

class-states

Manage async complexity with states

Example

import { States, PickState } from 'class-states'

type SomeConnectionState =
  {
    state: 'DISCONNECTED'    
  } | {
    state: 'CONNECTING',
    transition: Promise<
      PickState<SomeConnectionState, 'CONNECTED' | 'DISCONNECTED'>
    >
  } | {
    state: 'CONNECTED',
    connection: Connection
  }

class SomeConnection {
  state: States<SomeConnectionState>
  constructor() {
    this.state = new States({
        state: 'DISCONNECTED'
    })
    this.state.onTransition((state, prevState) => {})
    this.state.onTransition('DISCONNECTED', (disconnectedState, prevState) => {})
  }
  private _connect() {
    return this.state.set({
      state: 'CONNECTING',
      transition: someConnectionCreator()
        .then((connection) => ({
          state: 'CONNECTED',
          connection
        }))
        .catch(() => ({
          state: 'DISCONNECTED'
        }))
    })
  }
  async connect() {
    // We first narrow down to a possible "CONNECTED" or "DISCONNECTED"
    // state
    const connectState =  await this.state.matches({
      DISCONNECTED: () => this._connect().transition,
      CONNECTING: ({ transition }) => transition,
      CONNECTED: (state) => state
    })
    
    // Then we use the narrowed state to evaluate what this method
    // returns
    return this.state.matches(connectState, {
      CONNECTED: ({ connection }) => connection,
      DISCONNECTED: () => {
        throw new Error("Could not connect")
      }
    })
  }
  disconnect() {
      this.state.matches({
          CONNECTED: ({ connection }) => {
              connection.dispose()
          },
          _: () => {
              // Do nothing
          }
      })
  }
}

Why?

When you work with complex asynchronous code you have some challenges:

  1. Async function/method calls can be called when they are already running, which is easy to ignore or forget to evaluate

  2. You have multiple flags that has a relationship (isConnecting, isConnected), but needs to be manually orchestrated, risking invalid states

  3. Values can often also be null or undefined as they are asynchronously initialized

class-states gives you a tiny abstraction of explicit states and a matches utility which:

  1. Forces you to evaluate how any function/method runs when consuming the state of the class

  2. Explicit single states instead of manually orchestrating multiple flags

  3. Values tied to states are consumed on the specific state, avoiding null and undefined unions

class-states's People

Contributors

christianalfoni avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.