@ssense/promise-pool
Promise Pool
class Pool
The idea behind a promise pool is that you want to handle a large volume of promises but you do not want to use Promise.all
because it is an all or nothing approach. The promise pool allows you to execute a large number of promises concurrently and if any promise is to fail it will continue the execution of the promises uninterupted.
Also you can specify the number of promises that should be run in parallel to prevent overwhelming the function that is servicing your asynchronous requests. (see examples here)
Methods
constructor(generator: PromiseGenerator , max: number ) | PromisePool | Creates a new instance of PromisePool |
onResolved(callback: (data: any , index: number ) => void ) | PromisePool | Adds a callback called every time a promise in the pool is resolved |
onRejected(callback: (err: Error , index: number ) => void) | PromisePool | Adds a callback called every time a promise in the pool is rejected |
run() | Promise<PromisePoolStats> | Starts the pool of promises, returning statistics about execution when finished |
Details
constructor(generator: PromiseGenerator, max: number)
Creates a new instance of PromisePool
Parameters
generator | PromiseGenerator | Yes | Function that should return a promise on each call, or null if all promises are executed |
max | number | Yes | Maximum number of parallel promises to run |
onResolved(callback: (data: any, index: number) => void)
Adds a callback called every time a promise in the pool is resolved
Parameters
callback | Function | Yes | Function called every time a promise in the pool is resolved, receiving in parameter the promise return value, as well as the promise index in the pool |
Return value
PromisePool | The current PromisePool instance |
onRejected(callback: (err: Error, index: number) => void)
Adds a callback called every time a promise in the pool is rejected
Parameters
callback | Function | Yes | Function called every time a promise in the pool is rejected, receiving in parameter the error, as well as the promise index in the pool |
Return value
PromisePool | The current PromisePool instance |
run()
Starts the pool of promises, returning statistics about execution when finished
Return value
Promise<PromisePoolStats> | Statistics about current pool execution |
PromisePoolStats properties
resolved | number | Yes | Number of resolved promises after current pool run |
rejected | number | Yes | Number of rejected promises after current pool run |
duration | number | Yes | Current pool run duration in milliseconds |
Examples
import { Pool } from '@ssense/promise-pool';
let i = 0;
const generator = (): any => {
i += 1;
if (i > 10) {
return null;
}
return new Promise<number>((resolve, reject) => {
const current = i;
setTimeout(() => {
return current % 2 === 0 ? resolve(current) : reject(new Error(current.toString()));
}, 2);
});
};
const pool = new Pool(generator, 2);
const result = await pool.run();