Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@supercharge/promise-pool

superchargejs2mMIT3.2.0TypeScript support: included

Map-like, concurrent promise processing for Node.js

supercharge, superchargejs, promise-pool, nodejs, async, map, async-map, promises

readme



Promise Pool

Map-like, concurrent promise processing for Node.js.


Installation · Docs · Usage



Latest Version Monthly downloads

Follow @marcuspoehls and @superchargejs for updates!


Installation

npm i @supercharge/promise-pool

Docs

Usage

Using the promise pool is pretty straightforward. The package exposes a class and you can create a promise pool instance using the fluent interface.

Here’s an example using a concurrency of 2:

import { PromisePool } from '@supercharge/promise-pool'

const users = [
  { name: 'Marcus' },
  { name: 'Norman' },
  { name: 'Christian' }
]

const { results, errors } = await PromisePool
  .withConcurrency(2)
  .for(users)
  .process(async (userData, index, pool) => {
    const user = await User.createIfNotExisting(userData)

    return user
  })

The promise pool uses a default concurrency of 10:

await PromisePool
  .for(users)
  .process(async data => {
    // processes 10 items in parallel by default
  })

Manually Stop the Pool

You can stop the processing of a promise pool using the pool instance provided to the .process() and .handleError() methods. Here’s an example how you can stop an active promise pool from within the .process() method:

await PromisePool
  .for(users)
  .process(async (user, index, pool) => {
    if (condition) {
      return pool.stop()
    }

    // processes the `user` data
  })

You may also stop the pool from within the .handleError() method in case you need to:

import { PromisePool } from '@supercharge/promise-pool'

await PromisePool
  .for(users)
  .handleError(async (error, user, pool) => {
    if (error instanceof SomethingBadHappenedError) {
      return pool.stop()
    }

    // handle the given `error`
  })
  .process(async (user, index, pool) => {
    // processes the `user` data
  })

Bring Your Own Error Handling

The promise pool allows for custom error handling. You can take over the error handling by implementing an error handler using the .handleError(handler).

If you provide an error handler, the promise pool doesn’t collect any errors. You must then collect errors yourself.

Providing a custom error handler allows you to exit the promise pool early by throwing inside the error handler function. Throwing errors is in line with Node.js error handling using async/await.

import { PromisePool } from '@supercharge/promise-pool'

try {
  const errors = []

  const { results } = await PromisePool
    .for(users)
    .withConcurrency(4)
    .handleError(async (error, user) => {
      if (error instanceof ValidationError) {
        errors.push(error) // you must collect errors yourself
        return
      }

      if (error instanceof ThrottleError) { // Execute error handling on specific errors
        await retryUser(user)
        return
      }

      throw error // Uncaught errors will immediately stop PromisePool
    })
    .process(async data => {
      // the harder you work for something,
      // the greater you’ll feel when you achieve it
    })

  await handleCollected(errors) // this may throw

  return { results }
} catch (error) {
  await handleThrown(error)
}

Callback for Started and Finished Tasks

You can use the onTaskStarted and onTaskFinished methods to hook into the processing of tasks. The provided callback for each method will be called when a task started/finished processing:

import { PromisePool } from '@supercharge/promise-pool'

await PromisePool
  .for(users)
  .onTaskStarted((item, pool) => {
    console.log(`Progress: ${pool.processedPercentage()}%`)
    console.log(`Active tasks: ${pool.processedItems().length}`)
    console.log(`Active tasks: ${pool.activeTasksCount()}`)
    console.log(`Finished tasks: ${pool.processedItems().length}`)
    console.log(`Finished tasks: ${pool.processedCount()}`)
  })
  .onTaskFinished((item, pool) => {
    // update a progress bar or something else :)
  })
  .process(async (user, index, pool) => {
    // processes the `user` data
  })

You can also chain multiple onTaskStarted and onTaskFinished handling (in case you want to separate some functionality):

import { PromisePool } from '@supercharge/promise-pool'

await PromisePool
  .for(users)
  .onTaskStarted(() => {})
  .onTaskStarted(() => {})
  .onTaskFinished(() => {})
  .onTaskFinished(() => {})
  .process(async (user, index, pool) => {
    // processes the `user` data
  })

Task Timeouts

Sometimes it’s useful to configure a timeout in which a task must finish processing. A task that times out is marked as failed. You may use the withTaskTimeout(<milliseconds>) method to configure a task’s timeout:

import { PromisePool } from '@supercharge/promise-pool'

await PromisePool
  .for(users)
  .withTaskTimeout(2000) // milliseconds
  .process(async (user, index, pool) => {
    // processes the `user` data
  })

Notice: a configured timeout is configured for each task, not for the whole pool. The example configures a 2-second timeout for each task in the pool.

Correspond Source Items and Their Results

Sometimes you want the processed results to align with your source items. The resulting items should have the same position in the results array as their related source items. Use the useCorrespondingResults method to apply this behavior:

import { setTimeout } from 'node:timers/promises'
import { PromisePool } from '@supercharge/promise-pool'

const { results } = await PromisePool
  .for([1, 2, 3])
  .withConcurrency(5)
  .useCorrespondingResults()
  .process(async (number, index) => {
    const value = number * 2

    return await setTimeout(10 - index, value)
  })

/**
 * source array: [1, 2, 3]
 * result array: [2, 4 ,6]
 * --> result values match the position of their source items
 */

For example, you may have three items you want to process. Using corresponding results ensures that the processed result for the first item from the source array is located at the first position in the result array (=index 0). The result for the second item from the source array is placed at the second position in the result array, and so on …

Return Values When Using Corresponding Results

The results array returned by the promise pool after processing has a mixed return type. Each returned item is one of this type:

  • the actual value type: for results that successfully finished processing
  • Symbol('notRun'): for tasks that didn’t run
  • Symbol('failed'): for tasks that failed processing

The PromisePool exposes both symbols and you may access them using

  • Symbol('notRun'): exposed as PromisePool.notRun
  • Symbol('failed'): exposed as PromisePool.failed

You may repeat processing for all tasks that didn’t run or failed:

import { PromisePool } from '@supercharge/promise-pool'

const { results, errors } = await PromisePool
  .for([1, 2, 3])
  .withConcurrency(5)
  .useCorrespondingResults()
  .process(async (number) => {
    // …
  })

const itemsNotRun = results.filter(result => {
  return result === PromisePool.notRun
})

const failedItems = results.filter(result => {
  return result === PromisePool.failed
})

When using corresponding results, you need to go through the errors array yourself. The default error handling (collect errors) stays the same and you can follow the described error handling section above.

Contributing

  1. Create a fork
  2. Create your feature branch: git checkout -b my-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request 🚀

License

MIT © Supercharge


superchargejs.com  ·  GitHub @supercharge  ·  Twitter @superchargejs

changelog

Changelog

3.2.0 - 2024-03-25

Added

  • add "sideEffects": false to package.json #83

Updated

  • updated types for the handler function in the promise pool processor

Updated

  • bump dependencies

3.1.1 - 2024-01-31

Updated

  • bump dependencies

Fixed

3.1.0 - 2023-09-25

Added

  • clear timers from task timeouts to remove them from the event loop: this is helpful to clear up resources for long-running timeouts and fastly resolving tasks. If not cleared, the timeouts stay in the event loop until they’re due
  • add keep error handler when calling pool.handleError after pool.for: previously the error handler was lost

Updated

  • bump dependencies

3.0.0 - 2023-07-09

Added

  • Accept iterables and async iterables and not just arrays
  • add performance testing script in performance directory: this is helpful to detect whether the promise pool is significantly slower than Promise.all

Updated

Breaking Changes

  • require Node.js v16
  • require ecmaScript 2021
  • the pool.items() method changed from the narrower type T[] to the wider type T[] | Iterable<T> | AsyncIterable<T> which might be a breaking change for your code base

2.4.0 - 2023-02-10

Added

Updated

  • bump dependencies
  • refined types when a promise or non-promise resuult will be handled

2.3.2 - 2022-08-05

Fixed

  • remove active task after handling the result or error #51
    • we previously removed the active tasks before handling the result or error, which caused the pool to pick up the next task too early

2.3.1 - 2022-08-05

Updated

  • bump dependencies

Fixed

  • stop processing items after throwing an error from inside the pool.handleError() method #51

2.3.0 - 2022-06-08

Added

  • pool.useConcurrency(<num>): adjust the concurrency of a running pool

Updated

  • bump dependencies

2.2.0 - 2022-05-20

Added

  • pool.onTaskStarted((item, pool) => { … }): configure a callback that runs when an item is about to be processed
  • pool.onTaskFinished((item, pool) => { … }): configure a callback that runs when an item finished processing

Updated

  • bump dependencies

2.1.0 - 2021-12-14

Added

  • keep the original error in error.raw
    • this is useful if your errors store some kind of context
    • the PromisePoolError instance would otherwise loose the original error context
class CustomError extends Error { … }

const { errors } = await PromisePool
  .withConcurrency(2)
  .for([1, 2, 3])
  .process(() => {
    throw new CustomError('Oh no')
  })

errors[0].raw instanceof CustomError
// true

Updated

  • bump dependencies
  • run tests for Node.js v17

2.0.0 - 2021-11-09

Breaking Changes

The 2.x release line changes the exports of this package:

// Now: 2.x
import { PromisePool } from '@supercharge/promise-pool'
// or
const { PromisePool } = require('@supercharge/promise-pool')

// Before: 1.x
import PromisePool from '@supercharge/promise-pool' // required the `esModuleInterop` flag in tsconfig.json
// or
const PromisePool = require('@supercharge/promise-pool')

The 1.x releases used CommonJS- and ESM-compatible default exports. That required TypeScript packages using ESM imports to enable the esModuleInterop flag in their tsconfig.json file. The named exports in 2.x don’t require that flag anymore.

1.9.0 - 2021-11-03

Added

  • pool.stop() method
  • add downlevelIteration: true option to tsconfig.json

Updated

  • bump dependencies
  • use UVU and c8 for testing (instead of Jest)
  • refined example output (in examples/promise-pool.js)
  • extend README with examples on how to stop an active promise pool

1.8.0 - 2021-09-24

Added

  • test code on Node.js v16
  • provide index as the second argument in the process function
      await PromisePool
        .withConcurrency(2)
        .for([1,2,3,4])
        .process(async (num, index) => {
          // processing …
        })

Updated

  • bump dependencies

Removed

  • testing on Node.js v15

1.7.0 - 2021-04-11

Updated

  • bump dependencies
  • refactored code to not use the @supercharge/goodies package

Removed

  • dependency to @supercharge/goodies

1.6.2 - 2021-04-09

Updated

  • bump dependencies

Fixed

  • missing concurrency in certain cases when not calling .withConcurrency()

1.6.1 - 2021-03-28

Fixed

  • typing error when processing a promise pool that was created from non-static methods

1.6.0 - 2020-11-03

Added

  • .handleError(handler) method: aka “bring your own error handling”. This allows you to take over error handling from the pool. If you impelement the .handleError method, the pool won’t collect errors anymore. It puts error handling in your hands.

Updated

  • bump dependencies

Fixed

  • failed tasks are handled properly now and the pool ensures the concurrency limit. Before, the pool started to process all items as soon as one failed

1.5.0 - 2020-09-20

Updated

  • bump dependencies
  • return types for results and errors now resolve properly for sync and async action handlers

1.4.0 - 2020-09-17

Added

  • improved types supporting typed return values
  • improved error handling when rejecting a promise without an error instance (thank you wzh)

Updated

  • bump dependencies
  • change main entrypoint in package.json to dist folder
  • move test runner from @hapi/lab to jest
  • move assertions from @hapi/code to jest

1.3.0 - 2020-07-16

Added

  • TypeScript typings

Updated

  • bump dependencies
  • moved code base to TypeScript to automatically generate type definitions

1.2.0 - 2019-10-15

Added

  • static methods for .withConcurrency and .for
    • moves boilerplate from your code to the promise pool package
    • new Pool().for(items) is now Pool.for(items))
    • new Pool().withConcurrency(2) is now Pool.withConcurrency(2))
    • it’s always the details :)

Updated

  • bump dependencies

1.1.1 - 2019-09-24

Updated

  • bump dependencies
  • move package docs to Supercharge docs

1.1.0 - 2019-08-14

Added

  • module.exports.default

Updated

  • bump dependencies
  • update NPM scripts

1.0.0 - 2019-07-15

Added

  • 1.0.0 release 🚀 🎉