UNPKG

5.43 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.
19```javascript
20const { Batcher } = require('promise-batcher');
21let runCount = 0;
22const batcher = new Batcher({
23 batchingFunction: (nums) => {
24 runCount++;
25 return Promise.resolve(nums.map((n) => {
26 return n + 1;
27 }));
28 }
29});
30const inputs = [1, 3, 5, 7];
31// Start a series of individual requests
32const promises = inputs.map((input) => batcher.getResult(input));
33// Wait for all the requests to complete
34Promise.all(promises).then((results) => {
35 console.log(results); // [ 2, 4, 6, 8 ]
36 // The requests were still done in a single run
37 console.log(runCount); // 1
38});
39```
40
41### Database Example
42
43This 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.
44```javascript
45const { Batcher } = require('promise-batcher');
46const batcher = new Batcher({
47 batchingFunction: (recordIds) => {
48 // Perform a batched request to the database with the inputs from getResult()
49 return database.batchGet(recordIds).then((results) => {
50 // Interpret the results from the request, returning an array of result values
51 return results.map((result) => {
52 if (result.success) {
53 // Resolve the individual request
54 return result.data;
55 } else {
56 // Reject the individual request (eg. record not found)
57 return new Error(result.message);
58 }
59 });
60 });
61 }
62});
63const recordIds = ["ABC123", "DEF456", "HIJ789"];
64// Start a series of individual requests
65const promises = recordIds.map((recordId) => batcher.getResult(recordId));
66// Wait for all the requests to complete
67Promise.all(promises).then((results) => {
68 // Use the results
69});
70```
71
72## API Reference
73
74### Object: Batcher
75
76A tool for combining requests.
77
78#### Constructor
79
80**new Batcher(options)** - Creates a new batcher.
81 * 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.
82 * 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)*.
83 * options.**maxBatchSize** - The maximum number of requests that can be combined in a single batch *(optional)*.
84 * 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 *(optional)*.
85 * 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)*.
86
87#### Methods
88
89* batcher.**getResult**(input) - Returns a promise which resolves or rejects with the individual result returned from the batching function..
90
91## License
92
93The MIT License (MIT)
94
95Copyright (c) 2017 Wes van Vugt
96
97Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
98
99The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
100
101THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.