forked from wuyawei/fe-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromise6.js
More file actions
77 lines (71 loc) · 1.91 KB
/
Copy pathpromise6.js
File metadata and controls
77 lines (71 loc) · 1.91 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
76
77
/**
* 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;
};
if(this.status === 'PENDING') {
let transition = (status, val) => {
setTimeout(_ => {
this.status = status;
let f = status === 'FULFILLED',
queue = this[f ? 'resolves' : 'rejects'];
queue.forEach(fn => val = fn(val) || val);
this[f ? 'value' : 'reason'] = val;
});
};
function resolve(value) {
transition('FULFILLED', value);
}
function reject(reason) {
transition('REJECTED', 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 resolve + '111111';
}, reject => {
console.log(reject);
return 'erro';
}).then(resolve => {
console.log(resolve);
}, reject => {
console.log(reject);
});