Promise Blocking Queue
Memory optimized promise blocking queue with concurrency control, specially designed to handle large data sets that must be consumed using streams.
Useful for rate-limiting async (or sync) operations that consume large data sets. For example, when interacting with a REST API or when doing CPU/memory intensive tasks.
If we use
Bluebird.map() for example, we are forced to load all the data in memory,
before being able to consume it - Out Of Memory Exception is right around the corner.
If we use p-queue (by the amazing sindresorhus) for example, we can utilize streams to avoid memory bloat, but we have no (easy) way to control the stream flow without hitting that Out Of Memory Exception.
The solution - a blocking queue that returns a promise that will be resolved when the added item gain an available slot in the queue, thus, allowing us to pause the stream consumption, until there is a real need to consume the next item - keeping us memory smart while maintaining concurrency level of data handling.
npm install promise-blocking-queue
Let's assume we have a very large (a couple of GBs) file called
users.json which contains a long list of users we want to add to our DB.
Also, let's assume that our DB instance it very cheap, and as such we don't want to load it to much, so we only want to handle
100 concurrent DB insert operations.
We can achieve a short scalable solution like:
Returns a new
queue instance, which is an
Adds a sync or async task to the queue
A promise that will be resolved when the queue has an available slot to run the task.
Used to realize that it is a good time to add another task to the queue.
A promise that will be resolved with the result of
Promise/Value returning function.
The arguments to pass to the function
The number of promises that are currently running.
The number of promises that are waiting to run.
Emitted when the queue becomes empty. Useful if, for example, you add additional items at a later time.
Emitted when the queue becomes empty, and all promises have completed:
queue.activeCount === 0 && queue.pendingCount === 0.
The difference with
empty is that
idle guarantees that all work from the queue has finished.
empty merely signals that the queue is empty, but it could mean that some promises haven't completed yet.
Promise Blocking Queue supports Node 6 LTS and higher.
All contributions are happily welcomed!
Please make all pull requests to the
master branch from your fork and ensure tests pass locally.