promax
Another promise limiter (adding concurrency to promises). This library uses rxjs to control concurrency, it also adds a little bit of extra functionality around how you get the results.
Setup Instructions
To install this package, run,
npm install --save promax
Usage Instructions
Once it's installed, you can use Promax
to run your promises with a specified concurrency value.
Assume we have the following promise function:
function somePromiseFunction ( returns = null , timeout = 0 ) {
return new Promise ( resolve => {
setTimeout ( ( ) => {
resolve ( returns ) ;
} , timeout ) ;
} ) ;
}
Promax is able to run this function concurrently in multiple ways:
import { Promax } from ' promax ' ;
async function run ( ) {
const limit = 2 ;
const expectedValues = [ 1 , 2 , 3 ] ;
const promax = Promax . create ( limit ) . add (
expectedValues . map ( ev => ( ) => somePromiseFunction ( ev ) )
) ;
const results = await promax . run ( ) ;
const resultMap = promax . getResultMap ( ) ;
}
NOTE: In this case, if a promise is rejected, it'll throw an error and end the call.
If we don't want to throw an error, we can pass a parameter object with throws: false
to the create function:
import { Promax } from ' promax ' ;
async function run ( ) {
const limit = 2 ;
const expectedValues = [ 1 , 2 , 3 ] ;
const promax = Promax . create ( limit , { throws : false } ) . add (
expectedValues . map ( ev => ( ) => somePromiseFunction ( ev ) )
) ;
}
When it doesn't throw, it wraps errored results in an ErrorResult
instance. Using instanceof ErrorResult
will tell you whether or not there was an error in your array of results. Let's assume we have the following promise function which rejects:
function someFailingPromiseFunction ( returns = 0 , timeout = 0 ) {
return new Promise ( ( resolve , reject ) => {
setTimeout ( ( ) => {
reject ( returns ) ;
} , timeout ) ;
} ) ;
}
Then we may get the following:
import { Promax } from ' promax ' ;
async function run ( ) {
const limit = 2 ;
const promax = Promax . create ( limit , { throws : false } ) . add ( [
( ) => somePromiseFunction ( 1 ) ,
( ) => someFailingPromiseFunction ( 2 ) ,
( ) => somePromiseFunction ( 3 ) ,
] ) ;
const results = await promax . run ( ) ;
const resultMap = promax . getResultMap ( ) ;
}
IMPORTANT: If you don't need the functionality above, you can chain everything into one call:
import { Promax } from ' promax ' ;
async function run ( ) {
const limit = 2 ;
const expectedValues = [ 1 , 2 , 3 ] ;
const results = Promax . create ( limit ) . add (
expectedValues . map ( ev => ( ) => somePromiseFunction ( ev ) )
) . run ( ) ;
}
And you can send in the result map by reference:
import { Promax } from ' promax ' ;
async function run ( ) {
const limit = 2 ;
const expectedValues = [ 1 , 2 , 3 ] ;
const resultMap = { valid : [ ] , error : [ ] } ;
const results = Promax . create ( limit )
. setResultMapOutput ( resultMap )
. add (
expectedValues . map ( ev => ( ) => somePromiseFunction ( ev ) )
) . run ( ) ;
}