1 | # seq
|
2 | Wraps an async (or other Promise returning) function to prevent it being
|
3 | executed 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
|
11 | 1. 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.
|
13 | 2. Any subsequent calls to the wrapped function before the original promise has
|
14 | completed, will return the same original promise.
|
15 | 3. Once the original promise resolves, the next call to the wrapped function
|
16 | will invoke the original function again.
|
17 |
|
18 | ### Arguments
|
19 | The inner function can optionally take any number of arguments. Parallel
|
20 | execution will be blocked **only** for calls with the same arguments. So two
|
21 | calls to `wrapped('foo')` will only result in the inner function being called
|
22 | once, but calls to `wrapped('foo')` and `wrapped('bar')` will both call the
|
23 | original function.
|
24 |
|
25 | ##### A note on performance
|
26 | Because the entire arguments array needs to be matched, using complex function
|
27 | signatures (e.g. many arguments or large objects) may impact performance
|
28 | somewhat. Try to keep your function signatures short and focused.
|
29 |
|
30 | ## Installation
|
31 | ```
|
32 | yarn add @woubuc/seq
|
33 | ```
|
34 |
|
35 | The library is written in Typescript so types are included.
|
36 |
|
37 | ## Usage
|
38 | ```typescript
|
39 | const 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 only one `fetch`
|
45 | // request will occur at any time. Each call to `wrapped()` below will resolve
|
46 | // with the same data.
|
47 | wrapped();
|
48 | wrapped();
|
49 | wrapped();
|
50 | ```
|
51 |
|
52 | ### With arguments
|
53 | ```typescript
|
54 | const 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 the inner function
|
60 | // once and so only one `fetch` request will occur with ID `1`.
|
61 | wrapped(1);
|
62 | wrapped(1);
|
63 |
|
64 | // However, the calls below will cause a second `fetch` request to occur because
|
65 | // the wrapped function is called with a different value.
|
66 | wrapped(2);
|
67 | wrapped(2);
|
68 | ```
|