• Stars
    star
    377
  • Rank 113,535 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 10 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Runs Promises in a pool that limits their concurrency.

ES6 Promise Pool

npm Bower CircleCI Build AppVeyor Build Coverage Status JavaScript Standard Style

Runs Promises in a pool that limits their concurrency.

Motivation

An ECMAScript 2015 Promise is a great way to handle asynchronous operations. The Promise.all function provides an easy interface to let a bunch of promises settle concurrently.

However, it's an all-or-nothing approach: all your promises get created simultaneously. If you have a ton of operations that you want to run with some concurrency, Promise.all is no good.

Instead, you probably want to limit the maximum number of simultaneous operations. That's where this module comes in. It provides an easy way of waiting for any number of promises to settle, while imposing an upper bound on the number of simultaneously executing promises.

The promises can be created in a just-in-time fashion. You essentially pass a function that produces a new promise every time it is called. Alternatively, you can pass an ES2015 iterator, meaning you can also use generator functions.

Compatibility

This module can be used both under Node.js and on the Web. If your platform does not have a native Promise implementation, you can use a polyfill such as ES6-Promise.

Installation

npm install --save es6-promise-pool
bower install --save es6-promise-pool
<script src="es6-promise-pool.js"></script>

Usage

// On the Web, leave out this line and use the script tag above instead.
var PromisePool = require('es6-promise-pool')

var promiseProducer = function () {
  // Your code goes here.
  // If there is work left to be done, return the next work item as a promise.
  // Otherwise, return null to indicate that all promises have been created.
  // Scroll down for an example.
}

// The number of promises to process simultaneously.
var concurrency = 3

// Create a pool.
var pool = new PromisePool(promiseProducer, concurrency)

// Start the pool.
var poolPromise = pool.start()

// Wait for the pool to settle.
poolPromise.then(function () {
  console.log('All promises fulfilled')
}, function (error) {
  console.log('Some promise rejected: ' + error.message)
})

Producers

The PromisePool constructor takes a Promise-producing function as its first argument. Let's first assume that we have this helper function that returns a promise for the given value after time milliseconds:

var delayValue = function (value, time) {
  return new Promise(function (resolve, reject) {
    console.log('Resolving ' + value + ' in ' + time + ' ms')
    setTimeout(function () {
      console.log('Resolving: ' + value)
      resolve(value)
    }, time)
  })
}

Function

Now, let's use the helper function above to create five such promises, which are each fulfilled after a second. Because of the concurrency of 3, the first three promises will be fulfilled after one second. Then, the remaining two will be processed and fulfilled after another second.

var count = 0
var promiseProducer = function () {
  if (count < 5) {
    count++
    return delayValue(count, 1000)
  } else {
    return null
  }
}

var pool = new PromisePool(promiseProducer, 3)

pool.start()
  .then(function () {
    console.log('Complete')
  })

Iterator

We can achieve the same result with ECMAScript 2015 iterators. Since ES2015 generator functions return such an iterator, we can make the example above a lot prettier:

const generatePromises = function * () {
  for (let count = 1; count <= 5; count++) {
    yield delayValue(count, 1000)
  }
}

const promiseIterator = generatePromises()
const pool = new PromisePool(promiseIterator, 3)

pool.start()
  .then(() => console.log('Complete'))

It's also possible to pass a generator function directly. In that case, it will be invoked with no arguments and the resulting iterator will be used. This feature will however be removed in version 3.

Events

We can also ask the promise pool to notify us when an individual promise is fulfilled or rejected. The pool fires fulfilled and rejected events exactly for this purpose.

var pool = new PromisePool(promiseProducer, concurrency)

pool.addEventListener('fulfilled', function (event) {
  // The event contains:
  // - target:    the PromisePool itself
  // - data:
  //   - promise: the Promise that got fulfilled
  //   - result:  the result of that Promise
  console.log('Fulfilled: ' + event.data.result)
})

pool.addEventListener('rejected', function (event) {
  // The event contains:
  // - target:    the PromisePool itself
  // - data:
  //   - promise: the Promise that got rejected
  //   - error:   the Error for the rejection
  console.log('Rejected: ' + event.data.error.message)
})

pool.start()
  .then(function () {
    console.log('Complete')
  })

Upgrading

Since version 2.0.0, this module does not depend on ES6-Promise anymore. If you want to support platforms without a native Promise implementation, please load a polyfill first.

If you prefer not to polyfill the global Promise for whatever reason, you can also pass your Promise class as an option instead:

var ES6Promise = require('es6-promise').Promise // or another implementation
var pool = new PromisePool(promiseProducer, concurrency, {promise: ES6Promise})

Alternatives

Author

Tim De Pauw

License

MIT

More Repositories

1

swirly

A marble diagram generator.
TypeScript
114
star
2

winston-aws-cloudwatch

A Winston transport for Amazon CloudWatch.
JavaScript
47
star
3

lwc

A live-updating version of the UNIX wc command.
Go
32
star
4

metalsmith-discover-partials

Discovers your template partials and registers them with Handlebars.
JavaScript
12
star
5

kodi-missing-episodes

Checks your Kodi TV library for missing episodes using Trakt.
TypeScript
9
star
6

metalsmith-discover-helpers

Discovers your template helpers and registers them with Handlebars.
JavaScript
9
star
7

rollup-timer

Times Rollup plugins by monkey-patching plugin API functions.
JavaScript
7
star
8

plugin.video.deredactie

Kodi plugin to watch videos from deredactie.be.
Python
7
star
9

jflow

Cover Flow for Java Swing.
Java
7
star
10

esbuild-plugin-import-pattern

esbuild plugin that imports modules based on wildcard patterns.
JavaScript
5
star
11

samovar

A pure-JSON template language and renderer. Also supports YAML.
JavaScript
5
star
12

rollup-load-plugins

Loads Rollup plugins listed in package.json.
JavaScript
4
star
13

http-aws4

Performs AWS Signature Version 4-signed HTTP requests from the command line.
JavaScript
4
star
14

asdf-bump

Interactive upgrades for asdf.
JavaScript
4
star
15

chicago-capitalize

Capitalizes a title according to the Chicago Manual of Style.
JavaScript
4
star
16

rollup-plugin-mustache

Precompiles Mustache templates using Hogan.js.
JavaScript
3
star
17

minivault

A pretty rudimentary vault (Web front end).
JavaScript
3
star
18

fancy-rollup

Multi-process Rollup wrapper.
JavaScript
3
star
19

atom-npm-helper

Search the npm registry and install packages from Atom.
JavaScript
3
star
20

aws-lambda-node-wrapper

Runs recent versions of Node.js on AWS Lambda.
JavaScript
3
star
21

hampster

Installs and links interdependent npm packages.
JavaScript
3
star
22

minivault-rest

A pretty rudimentary vault (RESTful API).
JavaScript
2
star
23

rollup-plugin-resolve-aliases

Resolves aliases.
JavaScript
2
star
24

picard

GitHub-style punchcards meet pie charts.
JavaScript
2
star
25

minivault-core

A pretty rudimentary vault (core API).
JavaScript
2
star
26

babel-preset-es2015-generators-async

babel-preset-es2015 minus regenerator plus async-to-module-method.
JavaScript
2
star
27

dune-movie-prettifier

Creates nice movie listings for Dune HD media players.
Perl
2
star
28

event-registry

Keeps track of EventEmitter listeners and automatically removes them upon selected events.
JavaScript
2
star
29

jquery-selecttext

jQuery plugin to select all text in an element
JavaScript
1
star
30

dune-tv-prettifier

Creates nice TV series listings for Dune HD media players.
Perl
1
star
31

rollup-plugin-strip-logger

Strips out references to a logger package.
JavaScript
1
star
32

regexfu

A simple Java Swing GUI to try out regular expressions.
Java
1
star
33

bucketeer

Bulk-processes objects inside an Amazon S3 bucket.
JavaScript
1
star
34

rollup-plugin-assert-es

Verifies that bundled code is ES5.
JavaScript
1
star
35

rollup-plugin-transform-code

Performs simple code transformations.
JavaScript
1
star
36

burrata

Robust, developer-friendly postMessage.
JavaScript
1
star
37

rollup-plugin-cssnext

Easy integration between Rollup and cssnext.
JavaScript
1
star
38

depviz

Visualizes intra-monorepo dependencies.
JavaScript
1
star
39

stream-capacitor

Throttles streams based on customizable throughput.
JavaScript
1
star
40

diagnosis

Runs a series of client-side health checks.
JavaScript
1
star
41

lwc-nodejs

A live-updating version of the UNIX wc command.
JavaScript
1
star
42

karma-mocha-iframes

Runs every Mocha-based Karma test in its own iframe.
JavaScript
1
star
43

mitmproxy-scripts

Scripts that I use with mitmproxy.
Python
1
star
44

yorkie

A pure-Bash port of Husky. Woof!
Shell
1
star