-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path25_co_lib_generator_sequential_fixed_steps.js
80 lines (64 loc) · 1.46 KB
/
25_co_lib_generator_sequential_fixed_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
79
80
'use strict';
var co = require("co"),
promisify = require("es6-promisify");
function run(useResult)
{
co(process);
function* process()
{
try {
var res = yield promisify(step1)();
res = yield promisify(step2)(res);
res = yield promisify(step3)(res);
useResult(null, res);
} catch(err) {
useResult(err);
}
}
function step1(done)
{
console.log('Step 1');
setTimeout(function()
{
var err = Math.random()*6 < 1 ? 'error in step 1' : null;
if(err)
return done(err);
var x = Math.random();
done(null, x);
}, 500);
}
function step2(x, done)
{
console.log('Step 2');
setTimeout(function()
{
var err = Math.random()*6 < 1 ? 'error in step 2' : null;
if(err)
return done(err);
x *= 2;
done(null, x);
}, 500);
}
function step3(x, done)
{
console.log('Step 3');
setTimeout(function()
{
var err = Math.random()*6 < 1 ? 'error in step 3' : null;
if(err)
return done(err);
x += 2;
done(null, x);
}, 500);
}
}
function print(res)
{
console.log('Result is ' + res);
}
run(function(err, res)
{
if(err)
return console.log('Catch: ' + err);
print(res);
});