Skip to content

Instantly share code, notes, and snippets.

@behrad
Created January 27, 2014 14:27
Show Gist options
  • Save behrad/8649455 to your computer and use it in GitHub Desktop.
Save behrad/8649455 to your computer and use it in GitHub Desktop.
Simple utility to run and collect multiple async functions callbacks
/**
* Data fetching helper.
*/
function get(obj) {
var pending = 0
, res = {}
, callback
, done;
return function _(arg) {
switch (typeof arg) {
case 'function':
callback = arg;
break;
case 'string':
++pending;
obj[arg](function (err, val) {
if (done) return;
if (err) return done = true, callback(err);
res[arg] = val;
--pending || callback(null, res);
});
break;
}
return _;
};
}
// example usage, considering queue object has the following callback based methods:
get(queue)
('inactiveCount')
('completeCount')
('activeCount')
('failedCount')
('delayedCount')
('workTime')
(function (err, obj) {
if (err) return res.send({ error: err.message });
res.send(obj);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment