Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

asyncforge

matteo.collina8.2kMIT0.5.0TypeScript support: included

asyncforge allows you to remove singletons from your codebase with the use of AsyncLocalStorage.

async, local, storage, asynclocalstorage, memo, forge, singleton

readme

asyncforge

asyncforge allows you to remove singletons from your codebase with the use of AsyncLocalStorage.

It provides helpers to build Next.js-style helpers to access "singletons".

Install

npm i asyncforge

Usage

import { create, memo } from 'asyncforge.js'

const a = memo()
const b = memo()

const store = create()

store.run(() => {
  a.set(42)
  b.set(123)

  // simulate an event loop turn
  setImmediate(() => {
    console.log('-- first event loop turn --')
    console.log('a', a())
    console.log('b', b())
  })
})

create(() => {
  a.set(43)
  b.set(321)

  // simulate an event loop turn
  setImmediate(() => {
    console.log('-- second event loop turn --')
    console.log('a', a())
    console.log('b', b())

    store.run(() => {
      setImmediate(() => {
        console.log('-- third event loop turn --')
        console.log('a', a())
        console.log('b', b())
      })
    })

    setImmediate(() => {
      store.enterWith()
      console.log('-- fourth event loop turn --')
      console.log('a', a())
      console.log('b', b())
    })
  })
})

TypeScript

You can call the asyncforge functions in a type-safe way:

import { create, memo } from "asyncforge";
const memoNum = memo<number>();
const test = memo<string>();

const store = create()

store.run(() => {
  // This is okay for TypeScript, since you're passing a number
  memoNum.set(123);


  // This will not build
  memoNum.set('wrong');
})

store.run(() => {
  // The `result` var will be of type `number`
  const result = memoNum()
})

License

MIT