-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path19_promise_parameters_sequential_var_steps.js
67 lines (56 loc) · 1.44 KB
/
19_promise_parameters_sequential_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
'use strict';
function run(multipliers, useResult)
{
new Promise(step1)
.then(step2)
.then(useResult)
.catch(function(err)
{
console.log('Catch: ' + err);
});
function step1(fulfil, reject)
{
console.log('Step 1');
setTimeout(function()
{
var err = Math.random()*6 < 1 ? 'error in step 1' : null;
if(err)
return reject(err);
var x = Math.random();
fulfil(x);
}, 500);
}
function step2(x)
{
console.log('Step 2');
return new Promise(function(fulfil, reject)
{
var pr = Promise.resolve(x);
for(var i in multipliers)
pr = pr.then(step2iter.bind(this, multipliers, i));
pr.then(fulfil)
.catch(reject);
});
}
function step2iter(multipliers, index, x)
{
var item = multipliers[index++];
console.log('Step 2, call #' + index);
return new Promise(function(fulfil, reject)
{
setTimeout(function()
{
var err = Math.random()*8 < 1 ? 'error in step 2 ix ' + index : null;
if(err)
return reject(err);
x *= item;
fulfil(x);
}, 500);
});
}
}
function print(res)
{
console.log('Result is ' + res);
}
run([5,7,2,4], print);