Created
December 9, 2010 07:11
-
-
Save akidee/734436 to your computer and use it in GitHub Desktop.
Instead of the serial end() - every item in the source list is processed after the previous one is ready - endParallel() makes parallel calls to a generator that uses filters that can be executed separately.
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
var async = require('asyncjs') | |
async.plugin({ | |
endParallel: function(callback) { | |
var source = this.source | |
var e | |
var min_i_err = Infinity | |
var first_e = null | |
var values = [] | |
var counter = 0 | |
var handler = function(i) { | |
return function(err, value) { | |
e = err | |
if (err) { | |
if (i < min_i_err) | |
min_i_err = i | |
first_e = err | |
/*if (err == STOP) | |
callback && callback(null, last) | |
else | |
callback && callback(err, value)*/ | |
} | |
else { | |
values[i] = value | |
} | |
process.nextTick(function() { | |
if (--counter == 0) | |
callback && callback(first_e == async.STOP ? null : first_e, values[values.length - 1]) | |
}) | |
} | |
} | |
do { | |
source.next(handler(counter++)) | |
} while (!e) | |
} | |
}) | |
var t | |
async.list([ | |
function(next) { | |
t = +new Date | |
async | |
.list([1,2,3,4,5,6,7]) | |
.filter(function(i, next) { | |
time = Math.round(Math.random() * 1000) | |
console.log(i, 'yet '+time) | |
setTimeout(function() { | |
console.log(i, 'now'); | |
next(null, i < 5); | |
}, time) | |
}) | |
.end(function(e, v) { | |
console.log('serial', arguments[1], +new Date - t) | |
next() | |
}) | |
}, | |
function(next) { | |
t = +new Date | |
async | |
.list([1,2,3,4,5,6,7]) | |
.filter(function(i, next) { | |
time = Math.round(Math.random() * 1000) | |
console.log(i, 'yet '+time) | |
setTimeout(function() { | |
console.log(i, 'now'); | |
next(null, i < 5); | |
}, time) | |
}) | |
.endParallel(function(e, v) { | |
console.log('parallel', arguments[1], +new Date - t) | |
next() | |
}) | |
} | |
]).call().end() |
Author
akidee
commented
Dec 9, 2010
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment