UNPKG

5.5 kBMarkdownView Raw
1# async-sema
2
3This is a semaphore implementation for use with `async` and `await`. The
4implementation follows the traditional definition of a semaphore rather than the
5definition of an asynchronous semaphore seen in some js community examples.
6Where as the latter one generally allows every defined task to proceed
7immediately and synchronizes at the end, async-sema allows only a selected
8number of tasks to proceed at once while the rest will remain waiting.
9
10Async-sema manages the semaphore count as a list of tokens instead of a single
11variable containing the number of available resources. This enables an
12interesting application of managing the actual resources with the semaphore
13object itself. To make it practical the constructor for Sema includes an option
14for providing an init function for the semaphore tokens. Use of a custom token
15initializer is demonstrated in `examples/pooling.js`.
16
17## Usage
18
19Firstly, add the package to your project's `dependencies`:
20
21```bash
22npm install --save async-sema
23```
24
25or
26
27```bash
28yarn add async-sema
29```
30
31Then start using it like shown in the following example. Check more
32use case examples [here](./examples).
33
34## Example
35
36```js
37const { Sema } = require('async-sema');
38const s = new Sema(
39 4, // Allow 4 concurrent async calls
40 {
41 capacity: 100 // Prealloc space for 100 tokens
42 }
43);
44
45async function fetchData(x) {
46 await s.acquire()
47 try {
48 console.log(s.nrWaiting() + ' calls to fetch are waiting')
49 // ... do some async stuff with x
50 } finally {
51 s.release();
52 }
53}
54
55const data = await Promise.all(array.map(fetchData));
56```
57
58The package also offers a simple rate limiter utilizing the semaphore
59implementation.
60
61```js
62const { RateLimit } = require('async-sema');
63
64async function f() {
65 const lim = RateLimit(5); // rps
66
67 for (let i = 0; i < n; i++) {
68 await lim();
69 // ... do something async
70 }
71}
72```
73
74## API
75
76### Sema
77
78#### Constructor(nr, { initFn, pauseFn, resumeFn, capacity })
79
80Creates a semaphore object. The first argument is mandatory and the second
81argument is optional.
82
83- `nr` The maximum number of callers allowed to acquire the semaphore
84 concurrently.
85- `initFn` Function that is used to initialize the tokens used to manage
86 the semaphore. The default is `() => '1'`.
87- `pauseFn` An optional fuction that is called to opportunistically request
88 pausing the the incoming stream of data, instead of piling up waiting
89 promises and possibly running out of memory.
90 See [examples/pausing.js](./examples/pausing.js).
91- `resumeFn` An optional function that is called when there is room again
92 to accept new waiters on the semaphore. This function must be declared
93 if a `pauseFn` is declared.
94- `capacity` Sets the size of the preallocated waiting list inside the
95 semaphore. This is typically used by high performance where the developer
96 can make a rough estimate of the number of concurrent users of a semaphore.
97
98#### async drain()
99
100Drains the semaphore and returns all the initialized tokens in an array.
101Draining is an ideal way to ensure there are no pending async tasks, for
102example before a process will terminate.
103
104#### nrWaiting()
105
106Returns the number of callers waiting on the semaphore, i.e. the number of
107pending promises.
108
109#### tryAcquire()
110
111Attempt to acquire a token from the semaphore, if one is available immediately.
112Otherwise, return `undefined`.
113
114#### async acquire()
115
116Acquire a token from the semaphore, thus decrement the number of available
117execution slots. If `initFn` is not used then the return value of the function
118can be discarded.
119
120#### release(token)
121
122Release the semaphore, thus increment the number of free execution slots. If
123`initFn` is used then the `token` returned by `acquire()` should be given as
124an argument when calling this function.
125
126### RateLimit(rps, { timeUnit, uniformDistribution })
127
128Creates a rate limiter function that blocks with a promise whenever the rate
129limit is hit and resolves the promise once the call rate is within the limit
130set by `rps`. The second argument is optional.
131
132The `timeUnit` is an optional argument setting the width of the rate limiting
133window in milliseconds. The default `timeUnit` is `1000 ms`, therefore making
134the `rps` argument act as requests per second limit.
135
136The `uniformDistribution` argument enforces a discrete uniform distribution over
137time, instead of the default that allows hitting the function `rps` time and
138then pausing for `timeWindow` milliseconds. Setting the `uniformDistribution`
139option is mainly useful in a situation where the flow of rate limit function
140calls is continuous and and occuring faster than `timeUnit` (e.g. reading a
141file) and not enabling it would cause the maximum number of calls to resolve
142immediately (thus exhaust the limit immediately) and therefore the next bunch
143calls would need to wait for `timeWindow` milliseconds. However if the flow is
144sparse then this option may make the
145code run slower with no advantages.
146
147## Contributing
148
1491. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
1502. Move into the directory of the clone: `cd async-sema`
1513. Link it to the global module directory of Node.js: `npm link`
152
153Inside the project where you want to test your clone of the package, you can now either use `npm link async-sema` to link the clone to the local dependencies.
154
155## Author
156
157Olli Vanhoja ([@OVanhoja](https://twitter.com/OVanhoja))