UNPKG

5.65 kBMarkdownView Raw
1# promise-batcher
2
3A module for batching individual promises to improve their collective efficiency.
4
5For release notes, see the [CHANGELOG](https://github.com/baudzilla/promise-batcher/blob/master/CHANGELOG.md).
6
7## Installation
8
9npm install promise-batcher
10
11## Examples
12
13Promise batcher is useful for batching requests made from branching
14
15### Basic Example
16
17This example demonstrates a batcher which takes numbers as inputs, adds 1 to each and returns the result.
18Note that while the getResult function is called multiple times, the batching function is only run once.
19If the send method is not called, the batch will still be processed when Node.js idles.
20```javascript
21const { Batcher } = require('promise-batcher');
22let runCount = 0;
23const batcher = new Batcher({
24 batchingFunction: (nums) => {
25 runCount++;
26 return Promise.resolve(nums.map((n) => {
27 return n + 1;
28 }));
29 }
30});
31// Send the batch of requests. This step is optional.
32batcher.send();
33const inputs = [1, 3, 5, 7];
34// Start a series of individual requests
35const promises = inputs.map((input) => batcher.getResult(input));
36// Wait for all the requests to complete
37Promise.all(promises).then((results) => {
38 console.log(results); // [ 2, 4, 6, 8 ]
39 // The requests were still done in a single run
40 console.log(runCount); // 1
41});
42```
43
44### Database Example
45
46This example shows how a batcher could be used to combile individual requests made to a database. This is especially useful when the requests need to be made independently of each other, allowing the requests to be made individually, yet be processed as batches.
47Note that in a real-world example, it would be best to implement exponential backoff for retried requests by using a delayFunction.
48```javascript
49const { Batcher, BATCHER_RETRY_TOKEN } = require('promise-batcher');
50const batcher = new Batcher({
51 batchingFunction: (recordIds) => {
52 // Perform a batched request to the database with the inputs from getResult()
53 return database.batchGet(recordIds).then((results) => {
54 // Interpret the results from the request, returning an array of result values
55 return results.map((result) => {
56 if (result.error) {
57 if (result.error.retryable) {
58 // Retry the individual request (eg. request throttled)
59 return BATCHER_RETRY_TOKEN;
60 } else {
61 // Reject the individual request (eg. record not found)
62 return new Error(result.error.message);
63 }
64 } else {
65 // Resolve the individual request
66 return result.data;
67 }
68 });
69 });
70 }
71});
72// Send the batch of requests. This step is optional.
73batcher.send();
74const recordIds = ["ABC123", "DEF456", "HIJ789"];
75// Start a series of individual requests
76const promises = recordIds.map((recordId) => batcher.getResult(recordId));
77// Wait for all the requests to complete
78Promise.all(promises).then((results) => {
79 // Use the results
80});
81```
82
83## API Reference
84
85### Object: Batcher
86
87A tool for combining requests.
88
89#### Constructor
90
91**new Batcher(options)** - Creates a new batcher.
92 * options.**batchingFunction**(inputArray) - A function which is passed an array of request values, returning a promise which resolves to an array of response values. The request and response arrays must be of equal length. To reject an individual request, return an Error object (or class which extends Error) at the corresponding element in the response array. To retry an individual request, return the BATCHER\_RETRY\_TOKEN in the response array.
93 * options.**delayFunction**() - A function which can delay a batch by returning a promise which resolves when the batch should be run. If the function does not return a promise, no delay will be applied *(optional)*.
94 * options.**maxBatchSize** - The maximum number of requests that can be combined in a single batch *(optional)*.
95 * options.**queuingDelay** - The number of milliseconds to wait before running a batch of requests. This is used to allow time for the requests to queue up. Defaults to 1ms. This delay does not apply if the limit set by options.maxBatchSize is reached, or if batcher.send() is called. Note that since the batcher uses setTimeout to perform this delay, batches delayed by this will only be run when Node.js is idle, even if that means a longer delay *(optional)*.
96 * options.**queuingThresholds** - An array containing the number of requests that must be queued in order to trigger a batch request at each level of concurrency. For example [1, 5], would require at least 1 queued request when no batch requests are active, and 5 queued requests when 1 (or more) batch requests are active. Defaults to [1]. Note that the delay imposed by options.queuingDelay still applies when a batch request is triggered *(optional)*.
97
98#### Methods
99
100* batcher.**getResult**(input) - Returns a promise which resolves or rejects with the individual result returned from the batching function.
101* batcher.**send**() - Bypasses any queuingDelay set, while respecting all other limits imposed. If no other limits are set, this will result in the batchingFunction being run immediately. Note that batches will still be run even if this function is not called, once the queuingDelay or maxBatchSize is reached.
102
103## License
104
105[MIT](https://github.com/baudzilla/promise-batcher/blob/master/LICENSE)