Class PromiseChainingMap<TKey>

Class that allows you to chain promises for a given key. This is useful when:

  1. You need to run promises from synchronous code and don't need to look at the results.
  2. The promises to run, or at least precisely when to run them, are not known in advance.
  3. The promises need to be run sequentially, waiting for the previous one to finish.

An example of when this can be helpful is inside of React components. Component code is mostly synchronous, but you may need to run some asynchronous code. You can't use await inside of React component code in many situations, so you can use this class to chain promises together.

When promises are added to the map with a key, they will run in the order they were added to the map for that key. If a promise rejects, a warning will be logged and the chain will continue. If a promise is added while another promise in the map for that key is running, the new promise will be chained to the existing one.

Type Parameters

  • TKey = string

Constructors

Methods

Constructors

Methods

  • Adds a promise function to the map for a given key. If a promise is already running for the key, the new promise will be chained to the existing one. Once all promises for a key have settled, the map will be cleared for that key.

    Parameters

    • key: TKey

      Unique key to identify a distinct promise chain

    • promiseFunction: () => Promise<unknown>

      Function that returns a promise to add to the chain

    Returns void

  • Gets the current promise chain for the given key. This is mostly useful for testing. Normally you should just call addPromiseFunction and let the map handle the rest.

    Parameters

    • key: TKey

      Unique key to identify a distinct promise chain

    Returns undefined | Promise<unknown>

    The current promise chain for the key