-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
61 lines (53 loc) · 1.55 KB
/
index.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
61
var async = require('async');
function asyncTree({
functionArray = [],
concurrency = 1,
delay = 0,
eachCallback = ()=>{},
doneCallback = ()=>{}
}){
var q = async.priorityQueue(function (task, callback) {
//NOTE: very dumb delay!!
setTimeout(function(){
task.fn.bind(task.data)(callback);
}, task.delay || delay);
}, concurrency);
function finalResults(callback){
eachCallback(undefined, this.results);
callback();
}
functionArray.push(finalResults);
q.drain = doneCallback;
function eachOfItem(fnList, index, callback){
var parent = this;
function currentCallback(err, items){
var nextfn = index+2 === fnList.length
? function(cb){
fnList[index+1].bind(this)(cb);
}
: function(cb){
return eachOfItem.bind(this)(fnList, index+1, cb);
};
// maybe batch items here
items.forEach(item => {
var task = {
fn: nextfn,
data: { item }
};
if(!parent.results){
task.data.results = [item];
} else {
task.data.results = parent.results.concat(item);
}
q.push(task, fnList.length-index);
});
callback();
}
fnList[index].bind(this)(currentCallback);
}
q.push({
fn: function(callback){ eachOfItem.bind(this)(functionArray, 0, callback); },
data: { delay: 0 }
});
}
module.exports = asyncTree;