@woubuc/seq
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

seq

Wraps an async (or other Promise returning) function to prevent it being executed in parallel.

npm MIT licensed install size Typescript type definitions included

How it works

  1. When the wrapped function is called for the first time, the original function is called and the wrapper keeps track of the original promise.
  2. Any subsequent calls to the wrapped function before the original promise has completed, will return the same original promise.
  3. Once the original promise resolves, the next call to the wrapped function will invoke the original function again.

Arguments

The inner function can optionally take any number of arguments. Parallel execution will be blocked only for calls with the same arguments. So two calls to wrapped('foo') will only result in the inner function being called once, but calls to wrapped('foo') and wrapped('bar') will both call the original function.

A note on performance

Because the entire arguments array needs to be matched, using complex function signatures (e.g. many arguments or large objects) may impact performance somewhat. Try to keep your function signatures short and focused.

Installation

yarn add @woubuc/seq

The library is written in Typescript so types are included.

Usage

const wrapped = seq(async () => {
  let result = await fetch(...);
  return result.json();
});

// You can now call the wrapped function multiple times, but
// only one `fetch` request will occur at any time. Each call
// to `wrapped()` below will resolve with the same data.
wrapped();
wrapped();
wrapped();

With arguments

const wrapped = seq(async (id : number) => {
	let result = await fetch(...);
	return result.json();
});

// Just like before, these first two calls will only invoke
// the inner function once and so only one `fetch` request
// will occur with ID `1`.
wrapped(1);
wrapped(1);

// However, the calls below will cause a second `fetch`
// request to occur because the wrapped function is called
// with a different value.
wrapped(2);
wrapped(2);

Package Sidebar

Install

npm i @woubuc/seq

Weekly Downloads

6

Version

1.0.1

License

MIT

Unpacked Size

15.6 kB

Total Files

6

Last publish

Collaborators

  • woubuc