Callback wraps user-supplied callbacks. Supports

  • removing a callback either when calling remove or if the user handler returns Callback.REMOVE
  • calling custom onRemove hooks
  • debouncing (via wrap)
  • awaiting on an asynchronous handler and ensuring that the handler does not run concurrently to itself, i.e. subsequent invokes will be queued

Type Parameters

  • Args extends unknown[] = []

    The type of arguments that the callback expects.

Constructors

Properties

KEEP: typeof KEEP = ...

Possible return value for the handler.

Do not do anything. Same as not retuning anything from the function.

REMOVE: typeof REMOVE = ...

Possible return value for the handler.

Will remove this callback.

wrap: {} = wrapCallback

Wraps the given handler or callback as a callback, optionally debounced by the given debounce window.

If the argument is already a callback or an invoke method of a callback, then the wrapper will call that callback and return the same value as it. It will also set up the returned wrapper callback so that it is removed when the original (given) callback is removed. However, removing the returned wrapper callback will not cause the original callback (being wrapped) to be removed. If you want to do this, then do wrapper.onRemove(wrapped.remove).

Note that if the argument is a callback that's already debounced by a larger window, then debounceWindow will have no effect.

If non-0, the callback will be called at most every debounceWindow ms. The arguments it will be called with will be the last arguments the wrapper was called with.

invoke: (...args: Args) => Promise<void>

Call the handler with the given arguments.

If the handler is asynchronous, it awaits on it. Furthermore, calls will always wait for previous calls to this handler to complete first, i.e. it never runs concurrently to itself. If you need multiple calls to the async handler to run concurrently, then wrap it in a non-async function that does not await it.

The returned promise is rejected in two cases:

  • If the callback throws an error or returns a rejected Promise.
  • If the callback is removed after you call invoke but before the handler is actually called (while it's waiting in the queue to be called) In this case, the rejection reason is Callback.REMOVE.

LisnUsageError If the callback is already removed.

isRemoved: () => boolean

Returns true if the callback has been removed and cannot be called again.

onRemove: (fn: () => void) => void

Registers the given function to be called when the callback is removed.

You can call onRemove multiple times to register multiple hooks.

remove: () => void

Mark the callback as removed and call the registered onRemove hooks.

Future attempts to call it will result in LisnUsageError.