Skip to content

Instantly share code, notes, and snippets.

@ricardobeat
Created March 3, 2011 01:30
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ricardobeat/852143 to your computer and use it in GitHub Desktop.
Save ricardobeat/852143 to your computer and use it in GitHub Desktop.
simple semaphore for parallel async execution, with error handling.
function queue(name){
queue.q[name]++ || (queue.q[name] = 1);
return function(err){
if (err && queue.e[name]) queue.e[name](err);
else if (err) throw err;
process.nextTick(function(){
queue.q[name]--;
queue.check(name);
});
}
}
queue.__proto__ = {
q: {},
c: {},
e: {},
check: function(name){ queue.q[name] == 0 && queue.c[name](); },
done: function(name, fn){ queue.c[name] = fn; },
err: function(name, fn){ queue.e[name] = fn; }
}
/* -- test -- */
// mock async function
function somethingAsync(s, cb){
setTimeout(function(cb){ console.log(s); cb(); }, Math.random()*1000, cb);
};
somethingAsync('frist', queue('bacon'));
somethingAsync('second', queue('bacon'));
somethingAsync('third', queue('bacon'));
// throw an error along the way
setTimeout(function(){
queue('bacon')(new Error('damn it leroy'));
}, 200);
// called when all queued functions are done
queue.done('bacon', function(){
console.log('done!');
});
// error handler
queue.err('bacon', function(err){
console.log('something went wrong :(', err);
//throw err;
});
console.log('let\'s see:');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment