Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Socket
Sign inDemoInstall

congestion

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

congestion

Generator-based congestion control


Version published
Maintainers
1
Created
Source

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 = [/* long list of tasks */];
var doTask = function(task) {
	/* Do the task and return a Promise */
};

The simplest way is to do tasks in a loop:

while (tasks.length) {
	doTask(tasks.shift());
}
//Drawback: All tasks get executed asynchronously which may lead to CPU/memory exhaustion.

The other method is to run tasks sequentially:

tasks.reduce(function(p, task) {
	return p.then(function() {
		return doTask(task);
	});
}, Promise.resolve());
//Drawbacks:
//	Slow execution of tasks (one task at a time).
//	Node's process may exceed v8's memory limit due to the long chain of promises.
//	The code is a little complicated and hard to understand.

The more elegant approach is to take advantage of ES6 generators:

var co = require('co');
co(function*() {
	while (tasks.length) {
		yield doTask(tasks.shift());
	}
});
//Drawback: Slow execution of tasks (one task at a time).
//Benefits:
//	Low memory footprint.
//	Clean and readable code.

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()));
	}
});
//Benefits:
//	Efficient execution of tasks (10 tasks at a time)
//	Low memory footprint.
//	Clean and readable code.

License

congestion is released under the MIT license.

Keywords

FAQs

Package last updated on 09 Jan 2016

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc