-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathparallel.js
60 lines (53 loc) · 1.63 KB
/
parallel.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
var debug = require('debug')('crap:parallel');
//a parallel helper that works with callback style OR thenables
module.exports = function parallel(tasks, done) {
function executor(resolve, reject) {
var failed = false;
var results = {};
var num_complete = 0;
var keys = Object.keys(tasks);
debug('runing tasks: %s', keys);
if(!keys.length) {
if(resolve) resolve(results);
if(done) done(null, results);
return;
}
keys.forEach(function (name) {
var worker = tasks[name];
function cb(err, result) {
if(thenable) return;//callback style not allowed if thenable used!
if (err) fail(err);
else success.call(name, result);
}
var return_value = worker(cb);
var thenable = return_value && typeof return_value.then === "function";
if(thenable)
return_value.then(success.bind(name), fail);
});
function success(result){
var name = this; //cause we did .bind(name) above
debug('%s complete! %d/%d %s failed=%s', name, num_complete+1, keys.length, keys, failed);
if(failed) return;
num_complete++;
results[name] = result;
if(num_complete===keys.length) {
process.nextTick(function () {
if (resolve) resolve(results);
if (done) done(null, results);
})
}
}
function fail(err) {
debug('one fail! %s', keys);
if(failed) return;
failed = true;
process.nextTick(function(){
if (reject) reject(err);
if (done) done(err);
})
}
}
if(typeof Promise!=='undefined')
return new Promise(executor);
executor();
};