UNPKG

2.44 kBMarkdownView Raw
1# seq
2Wraps an async (or other Promise returning) function to prevent it being
3executed in parallel.
4
5[![npm](https://img.shields.io/npm/v/@woubuc/seq)](https://www.npmjs.com/package/@woubuc/seq)
6[![MIT licensed](https://img.shields.io/badge/license-MIT-green)](https://github.com/woubuc/seq/blob/master/LICENSE.txt)
7[![install size](https://packagephobia.com/badge?p=@woubuc/seq)](https://packagephobia.com/result?p=@woubuc/seq)
8![Typescript type definitions included](https://img.shields.io/npm/types/@woubuc/seq)
9
10## How it works
111. When the wrapped function is called for the first time, the original function
12 is called and the wrapper keeps track of the original promise.
132. Any subsequent calls to the wrapped function before the original promise has
14 completed, will return the same original promise.
153. Once the original promise resolves, the next call to the wrapped function
16 will invoke the original function again.
17
18### Arguments
19The inner function can optionally take any number of arguments. Parallel
20execution will be blocked **only** for calls with the same arguments. So two
21calls to `wrapped('foo')` will only result in the inner function being called
22once, but calls to `wrapped('foo')` and `wrapped('bar')` will both call the
23original function.
24
25##### A note on performance
26Because the entire arguments array needs to be matched, using complex function
27signatures (e.g. many arguments or large objects) may impact performance
28somewhat. Try to keep your function signatures short and focused.
29
30## Installation
31```
32yarn add @woubuc/seq
33```
34
35The library is written in Typescript so types are included.
36
37## Usage
38```typescript
39const wrapped = seq(async () => {
40 let result = await fetch(...);
41 return result.json();
42});
43
44// You can now call the wrapped function multiple times, but
45// only one `fetch` request will occur at any time. Each call
46// to `wrapped()` below will resolve with the same data.
47wrapped();
48wrapped();
49wrapped();
50```
51
52### With arguments
53```typescript
54const wrapped = seq(async (id : number) => {
55 let result = await fetch(...);
56 return result.json();
57});
58
59// Just like before, these first two calls will only invoke
60// the inner function once and so only one `fetch` request
61// will occur with ID `1`.
62wrapped(1);
63wrapped(1);
64
65// However, the calls below will cause a second `fetch`
66// request to occur because the wrapped function is called
67// with a different value.
68wrapped(2);
69wrapped(2);
70```