-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path07_vanillajs_parallel_limited_var_steps.js
78 lines (61 loc) · 1.6 KB
/
07_vanillajs_parallel_limited_var_steps.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'use strict';
function async(values, useResult)
{
setTimeout(step1, 500);
function step1()
{
console.log('Step 1');
var x = Math.random();
setTimeout(limitedParallel.bind(null, x, values, 2, nextSteps, useResult), 500);
}
function nextSteps(ref, values, index, done)
{
console.log('Starting step #' + (index+2));
var error = Math.random()*12 < 1 ? new Error('index ' + (index+2)) : null;
ref.data += values[index];
setTimeout(done.bind(null, error, index+1), 500+Math.random()*1000);
}
}
function limitedParallel(data, coll, limit, stepCb, resolveCb)
{
// wrap data just in case it's primitive, for the processors to manipulate
var dataRef = {
data: data
};
var completed = 0,
running = 0,
index = 0,
erred;
function done(err, index)
{
console.log('Finished step #' + (index+1));
++completed;
--running;
if(!erred && err)
{
erred = true;
return resolveCb(err);
}
if(!erred)
{
if(completed === coll.length)
resolveCb(dataRef.data);
else
next();
}
}
function next()
{
for(; running < limit && index < coll.length; ++running)
stepCb(dataRef, coll, index++, done);
}
// unleash limited # of beasts
next();
}
function print(res)
{
if(res instanceof Error)
return console.log('An error occured: ' + res.message);
console.log('Result is ' + res);
}
async([5,7,2,4], print);