Skip to content

Instantly share code, notes, and snippets.

@gimenete
Last active April 18, 2024 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gimenete/5299247 to your computer and use it in GitHub Desktop.
Save gimenete/5299247 to your computer and use it in GitHub Desktop.
Simple utility for parallel execution of asynchronous tasks in JavaScript
function collector() {
var c = {}, errors = {}, results = {}, pending = 1, callback = null
c.bind = function(name) {
pending++
return function(err, result) {
if (err) errors[name] = err
else results[name] = result
fireIfFinished()
}
}
c.collect = function(_callback) {
callback = _callback
fireIfFinished()
}
function fireIfFinished() {
pending--
if (pending === 0) {
callback(errors, results)
}
}
return c
}
var c = collector()
var fs = require('fs')
fs.stat(__dirname + "/collector.js", c.bind('foo')) // this file should exist. It is actually this file
fs.stat(__dirname + "/bar.js", c.bind('bar')) // this file should not exist
c.collect(function(errors, results) {
console.log('foo', results.foo)
console.log('bar', errors.bar)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment