Skip to content

Instantly share code, notes, and snippets.

@fillano
Created September 22, 2011 16:53
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 fillano/1235322 to your computer and use it in GitHub Desktop.
Save fillano/1235322 to your computer and use it in GitHub Desktop.
try another way to Do.parallel, inspired by Tim Caswell's howtonode blog articles
function Wait(fns, done) {
var count = 0;
var results = [];
this.getCallback = function(index) {
count++;
return (function(waitback) {
return function() {
var i=0,args=[];
for(;i<arguments.length;i++) {
args.push(arguments[i]);
}
args.push(waitback);
fns[index].apply(this, args);
};
})(function(result) {
results.push(result);
if(--count == 0) {
done(results);
}
});
}
}
var a = new Wait(
[
function(waitback){
console.log('done a');
var result = 500;
waitback(result)
},
function(waitback){
console.log('done b');
var result = 1000;
waitback(result)
},
function(waitback){
console.log('done c');
var result = 1500;
waitback(result)
}
],
function(results){
var ret = 0, i=0;
for(; i<results.length; i++) {
ret += results[i];
}
console.log('done all. result: '+ret);
}
);
var callbacks = [a.getCallback(0),a.getCallback(1),a.getCallback(0),a.getCallback(2)];
setTimeout(callbacks[0], 500);
setTimeout(callbacks[1], 1000);
setTimeout(callbacks[2], 1500);
setTimeout(callbacks[3], 2000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment