forked from wuyawei/fe-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromise5.js
More file actions
75 lines (72 loc) · 1.89 KB
/
Copy pathpromise5.js
File metadata and controls
75 lines (72 loc) · 1.89 KB
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
/**
* Created by wyw on 2018/12/17.
*/
function Promise(Fn){
this.value;
this.reason;
this.resolves = [];
this.rejects = [];
this.status = 'PENDING';
this.then = (onFulfilled, onRejected) => {
function success (value) {
return typeof onFulfilled === 'function' && onFulfilled(value) || value;
}
function erro (reason) {
return typeof onRejected === 'function' && onRejected(reason) || reason;
}
if (this.status === 'PENDING') {
this.resolves.push(success);
this.rejects.push(erro);
} else if (this.status === 'FULFILLED') {
success(this.value);
} else if (this.status === 'REJECTED') {
erro(this.reason);
}
return this;
};
let resolve = (value) =>{
if (this.status === 'PENDING') {
setTimeout(_ => {
this.status = 'FULFILLED';
this.resolves.forEach(fn => value = fn(value) || value);
this.reason = value;
});
}
};
let reject = (reason) =>{
if (this.status === 'PENDING') {
setTimeout(_ => {
this.status = 'REJECTED';
this.rejects.forEach(fn => reason = fn(reason) || reason);
this.reason = reason;
});
}
};
try {
Fn(resolve, reject);
}
catch(err) {
reject(err);
}
}
let getInfor = new Promise((resolve, reject) => {
setTimeout(_ => {
let ran = Math.random();
console.log(ran);
if (ran > 0.5) {
resolve('success');
} else {
reject('fail');
}
}, 200);
}).then(resolve => {
console.log(resolve);
return 0;
}, reject => {
console.log(reject);
return 'erro';
}).then(resolve => {
console.log(resolve);
}, reject => {
console.log(reject);
});