Created
January 27, 2014 14:27
-
-
Save behrad/8649455 to your computer and use it in GitHub Desktop.
Simple utility to run and collect multiple async functions callbacks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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