congestion
Generator-based congestion control suitable to use with co
Installation
npm install congestion
Use Case
Let's say we have a long list of asynchronous tasks needs be done (e.g. convert
lots of files, fetch lots of urls, and etc.):
var tasks = [];
var doTask = function(task) {
};
The simplest way is to do tasks in a loop:
while (tasks.length) {
doTask(tasks.shift());
}
The other method is to run tasks sequentially:
tasks.reduce(function(p, task) {
return p.then(function() {
return doTask(task);
});
}, Promise.resolve());
The more elegant approach is to take advantage of ES6 generators:
var co = require('co');
co(function*() {
while (tasks.length) {
yield doTask(tasks.shift());
}
});
The best solution is to utilize congestion module in the previous approach:
var co = require('co');
var congestion = require('congestion')(10);
co(function*() {
while (tasks.length) {
yield congestion.wait(doTask(tasks.shift()));
}
});
License
congestion is released under the MIT license.