Last active
April 18, 2024 17:59
-
-
Save gimenete/5299247 to your computer and use it in GitHub Desktop.
Simple utility for parallel execution of asynchronous tasks in JavaScript
This file contains 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
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