forked from engineer-man/youtube
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromises.js
104 lines (68 loc) · 1.79 KB
/
promises.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
const q = require('q');
// callback hell
step1((err, value1) => {
if (err) {
// handle error for step1
}
step2(value1, (err, value2) => {
if (err) {
// handle error for step2
}
step3(value2, (err, value3) => {
if (err) {
// handle error for step3
}
step4(value3, (err, value4) => {
if (err) {
// handle error for step4
}
step5(value4, (err, value5) => {
if (err) {
// handle error for step5
}
step6(value5, (err, value6) => {
if (err) {
// handle error for step6
}
// finally, do something with value6
console.log(value6);
});
});
});
});
});
});
// promise style
return step1()
.then(value1 => {
return step2(value1)
})
.then(value2 => {
return step3(value2)
})
.then(value3 => {
return step4(value3)
})
.then(value4 => {
return step5(value4)
})
.then(value5 => {
return step6(value5)
})
.then(value6 => {
// finally, do something with value6
console.log(value6);
})
.catch(err => {
// handle error for everything regardless of where it came from
});
// .then() example
return something_async_single_result()
.then(result => {
// do something with result
});
// .spread() example
return something_async_three_results()
.spread((result1, result2, result3) => {
// do something with each result
});