-
Notifications
You must be signed in to change notification settings - Fork 0
/
callback&promise.js
88 lines (75 loc) · 1.61 KB
/
callback&promise.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
function plus1(a, b) {
if (a == 0 || b == 0)
throw new Error('a or b is empty!');
return a + b;
}
function test1() {
let a = 1;
let b = 2;
let c = 3;
try {
let tmp1 = plus1(a, b);
let result = plus1(tmp1, c);
console.log(result);
} catch (e) {
console.log(e);
}
}
//callback(err,res)
function plus2(a, b, callback) {
if (a == 0 || b == 0)
callback('a or b is empty!', undefined);
else
callback(undefined, a + b);
}
function test2(callback){
let a = 1;
let b = 0;
let c = 3;
plus2(a, b, function(err,res){
if (err){
callback(err,undefined);
} else{
let tmp1 = res;
plus2(tmp1, c, function(err,res){
if (err){
callback(err,undefined);
} else {
let result = res;
callback(undefine,result);
}
})
}
})
}
// test2(function(err,res){
// if (err)
// console.log(err);
// else
// console.log(res);
// });
//
function plus2Promise(a, b){
return new Promise((resolve,reject) => {
plus2(a, b, function(err, res){
if (err)
reject(err);
else
resolve(res);
})
});
}
function *test3(){
let a = 1;
let b = 2;
let c = 3;
try {
let tmp1 = yield plus2Promise(a, b);
let result = yield plus2Promise(tmp1, c);
console.log(result);
} catch (e) {
console.log(e);
}
}
const co = require('co');
co(test3);