node package manager
Stop wasting time. Easily manage code sharing in your team. Create a free org »

parallomise

Parallomise

Run native javascript promises in parallel.

Requirements

Installation

npm install --save parallomise

Usage

new Parallomise(options)

Construct a new Parallomise.

  • options
    • maxConcurrents - N maximum tasks may run in parallel. Defaults to 10.

.add(fn, id)

Add a function to the queue. Returns the id.

  • fn - a function that returns a promise
  • id - identifier for this task, broadcasted in promiseFulfilled and promiseRejected events.

.on(evt, callback)

Extends event emitter. Events/callbacks are:

  • promiseFulfilled - emitted when a promise (one task) is fulfilled
    • callback(id, result)
      • id - id of task
      • result - result passed from promise resolver
  • promiseRejected - emitted when a promise (one task) is rejected
    • callback(id, error)
      • id - id of task
      • error - error passed from promise rejector

.run()

Run the suite of tasks. Returns a promise that, after all promises complete, is fulfilled with a results map, keys being task ids and values are objects like so:

  • fulfilled: true/false, whether the promise was fulfilled
  • rejected: true/false, whether the promise was rejected

Values are not passed to avoid memory leakage. Instead, listen for the promiseFulfilled event

Results are added in the order that the tasks were originally added to the parallomise.

.clear()

Clears/resets this parallomise instance. Cannot be called when this parallomise is running.

Example

 
let Parallomise = require('parallomise'),
    parallomise = new Parallomise();
 
function longIOOperation(a) {
  // returns a promise 
}
 
parallomise.add(longIOOperation.bind(null,1), 'op1');
parallomise.add(longIOOperation.bind(null,2), 'op2');
parallomise.add(longIOOperation.bind(null,3), 'op3');
 
parallomise.on('promiseFulfilled', (id, result) => {
  console.log('Finished ' + id + ' with result ' + result);
});
 
parallomise.on('promiseRejected', (id, e) => {
  console.log('Error in ' + id + '' + e.stack);
});
 
parallomise
  .run()
  .then(resultsIterator => {
    for (let result of resultsIterator) {
      console.log(result);
      /*
        {
          fulfilled: true
          rejected: false
        }
 
        {
          fulfilled: true
          rejected: false
        }
        {
          fulfilled: true
          rejected: false
        }
      */
    }
 
  });
 

Testing

grunt test