Concurrency utilities for Javascript.
asyncqueue
asyncqueue
is an asynchronous FIFO queue brokered by Promise
s.
Feed the queue with offer(item)
, and retrieve it with poll()
.
Because poll may be called on an empty queue, the returned
Promise
provides a way to suspend the poll until a rendezvous
with the next call to offer.
To illustrate its power and simplicity, below is an implementation
of a resource pool. We use the pool by passing it a closure, to
which the resource is applied, afterwards the resource goes back
into the pool, e.g.:
var withResource = createPool(10, () => new DbConnection);
withResource(conn => conn.sql('SELECT ...')).then(result => {
});
The implementation of createPool
.
var asyncqueue = require('conc').asyncqueue;
function createPool(cap, newResource) {
var queue = asyncqueue();
for (var i = 0; i < cap; i++) queue.offer(newResource());
return function(perform) {
return queue.poll().then(resource =>
perform(resource).finally(() =>
queue.offer(resource)));
};
}