forked from chitomanansala/promises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeneratorOne.js
121 lines (107 loc) · 3.12 KB
/
generatorOne.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
'use strict'
/*
To show how promise behave in different conditions.
*/
// Helper function for issuing a delay.
let delay = time =>
new Promise(resolve =>
setTimeout(resolve, time)
);
let sendError = false;
let promiseOne = x =>
new Promise((resolve,reject) => {
console.log('START: Processing Promise One');
if (sendError) {
reject('ERROR: Promise One');
} else {
delay(1000).then(() => {
console.log('END: Processing Promise One. Returning: ', x);
resolve(x);
});
}
});
let promiseTwo = x =>
new Promise(resolve => {
console.log('START: Processing Promise Two');
delay(1000).then(() => {
x += 10;
console.log('END: Processing Promise Two. Returning: ', x);
resolve(x);
});
});
let promiseThree = x =>
new Promise((resolve, reject) => {
console.log('START: Processing Promise Three');
if (sendError) {
reject('ERROR: Promise Three');
} else {
delay(1000).then(() => {
console.log('END: Processing Promise Three. Returning: ', x);
resolve(x);
});
}
});
function processOne(x) {
promiseOne(x)
.then(returnItem => {
console.log('Return Item from Promise One: %d', returnItem);
return promiseTwo(30 + returnItem);
})
.then(returnItem => {
console.log('Return Item from Promise Two: %d', returnItem);
return promiseThree(40 + returnItem);
})
.then(returnItem => {
console.log('Return Item from Promise three: %d', returnItem);
return returnItem;
})
.catch(err => {
console.log('Error is returned: ', err);
})
}
function processTwo(x) {
sendError = true;
promiseOne(x)
.then((returnItem) => {
promiseTwo(returnItem + 30);
})
.then(() => {
sendError = false;
return promiseThree(40 + x);
})
.catch(err => {
console.log('Error is returned: ', err);
sendError = false;
})
}
function processThree(x) {
promiseOne(x)
.then(returnItem => {
console.log('Return Item from Promise One: %d', returnItem);
promiseTwo(30 + returnItem);
})
.then(returnItem => {
console.log('Return Item from Promise Two: %d', returnItem);
promiseThree(40)
})
.catch(err => {
console.log('Error is returned: ', err);
})
}
function processFour(x) {
promiseOne(x)
.then(promiseTwo)
.then(promiseThree)
.catch(err => console.log('Error is returned: ', err))
}
function processFive(x) {
promiseOne(x)
.then(returnItem => {
console.log('2. Return Item: ', returnItem);
promiseTwo();
})
.then(
promiseThree
)
.catch(err => console.log('Error is returned: ', err))
}