Skip to content

Instantly share code, notes, and snippets.

@skepticfx
Created November 1, 2013 20:05
Show Gist options
  • Select an option

  • Save skepticfx/7271156 to your computer and use it in GitHub Desktop.

Select an option

Save skepticfx/7271156 to your computer and use it in GitHub Desktop.
Super Awesome Technique to simulate Synchronous Behavior in node.js (or) Looping asynchronous stuff synchronously a.k.a a Node.js Anti-Pattern
// Looping asynchronous stuff synchronously
// Lets say you have to do some asynchronous stuff, say scan() 'n' number of times but only synchronously in node.js
// You may end up doing this anti-pattern in node.js, because of performance and other stuffs.
var iterate = function(args, callback){
finish = 0;
loop(args, 0);
setImmediate(function() {
if(finish == 1) {
//Done, run callback
if(typeof callback == "function") {
callback(result);
}
} else {
//Not done, keep looping
setImmediate(arguments.callee);
}
});
}
iterate(100, console.log);
var iterate = function(args, count){
var HOST = ip;
var PORT = 443;
if(count > no_of_loops){
finish = 1;
return;
}
// Do your asynchronous stuff here
scan(args, function(){
// An happy Async programmer
});
scan.on('finish', function(){
iterate(args, count+1); // Add this on all event listeners as well.
});
scan.on('error', function(){
iterate(args, count+1); // Add this on all event listeners as well.
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment