| 1 | # throat
|
|---|
| 2 |
|
|---|
| 3 | Throttle the parallelism of an asynchronous, promise returning, function / functions. This has special utility when you set the concurrency to `1`. That way you get a mutually exclusive lock.
|
|---|
| 4 |
|
|---|
| 5 | [Professionally supported throat is now available](https://tidelift.com/subscription/pkg/npm-throat?utm_source=npm-throat&utm_medium=referral&utm_campaign=readme)
|
|---|
| 6 |
|
|---|
| 7 | [](https://github.com/ForbesLindesay/throat/actions/workflows/test.yml?query=branch%3Amaster)
|
|---|
| 8 | [](https://coveralls.io/github/ForbesLindesay/throat)
|
|---|
| 9 | [](https://rollingversions.com/ForbesLindesay/throat)
|
|---|
| 10 | [](https://www.npmjs.com/package/throat)
|
|---|
| 11 |
|
|---|
| 12 | ## Installation
|
|---|
| 13 |
|
|---|
| 14 | npm install throat
|
|---|
| 15 |
|
|---|
| 16 | ## API
|
|---|
| 17 |
|
|---|
| 18 | ### throat(concurrency)
|
|---|
| 19 |
|
|---|
| 20 | This returns a function that acts a bit like a lock (exactly as a lock if concurrency is 1).
|
|---|
| 21 |
|
|---|
| 22 | Example, only 2 of the following functions will execute at any one time:
|
|---|
| 23 |
|
|---|
| 24 | ```js
|
|---|
| 25 | const throat = require('throat')(2);
|
|---|
| 26 |
|
|---|
| 27 | const resA = throat(async () => {
|
|---|
| 28 | /* async stuff... */
|
|---|
| 29 | });
|
|---|
| 30 | const resB = throat(async () => {
|
|---|
| 31 | /* async stuff... */
|
|---|
| 32 | });
|
|---|
| 33 | const resC = throat(async () => {
|
|---|
| 34 | /* async stuff... */
|
|---|
| 35 | });
|
|---|
| 36 | const resD = throat(async () => {
|
|---|
| 37 | /* async stuff... */
|
|---|
| 38 | });
|
|---|
| 39 | const resE = throat(async () => {
|
|---|
| 40 | /* async stuff... */
|
|---|
| 41 | });
|
|---|
| 42 | ```
|
|---|
| 43 |
|
|---|
| 44 | ### throat(concurrency, worker)
|
|---|
| 45 |
|
|---|
| 46 | This returns a function that is an exact copy of `worker` except that it will only execute up to `concurrency` times in parallel before further requests are queued:
|
|---|
| 47 |
|
|---|
| 48 | ```js
|
|---|
| 49 | const throat = require('throat');
|
|---|
| 50 |
|
|---|
| 51 | const input = ['fileA.txt', 'fileB.txt', 'fileC.txt', 'fileD.txt'];
|
|---|
| 52 | const data = Promise.all(
|
|---|
| 53 | input.map(throat(2, (fileName) => readFile(fileName)))
|
|---|
| 54 | );
|
|---|
| 55 | ```
|
|---|
| 56 |
|
|---|
| 57 | Only 2 files will be read at a time, sometimes limiting parallelism in this way can improve scalability.
|
|---|
| 58 |
|
|---|
| 59 | ## Security contact information
|
|---|
| 60 |
|
|---|
| 61 | To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure.
|
|---|
| 62 |
|
|---|
| 63 | ## License
|
|---|
| 64 |
|
|---|
| 65 | MIT
|
|---|