forked from wuyawei/fe-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromise7.js
More file actions
96 lines (94 loc) · 2.81 KB
/
Copy pathpromise7.js
File metadata and controls
96 lines (94 loc) · 2.81 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* Created by wyw on 2018/12/17.
*/
// function Promise(Fn){
// this.value;
// this.reason;
// this.resolves = [];
// this.rejects = [];
// this.status = 'PENDING';
//
// 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);
// }
// }
//
// Promise.prototype.then = function(onFulfilled, onRejected) {
// let promise = this;
// return new Promise((resolve, reject) => {
// function success(value) {
// let val = typeof onFulfilled === 'function' && onFulfilled(value) || value;
// if(val && typeof val['then'] === 'function'){ // 判断是否有then方法
// val.then(function(value){ // 如果返回的是Promise 则直接执行得到结果后再调用后面的then方法
// resolve(value);
// },function(reason){
// reject(reason);
// });
// }else{
// resolve(val);
// }
// }
// function erro (reason) {
// let rea = typeof onRejected === 'function' && onRejected(reason) || reason;
// reject(rea);
// }
// if (promise.status === 'PENDING') {
// promise.resolves.push(success);
// promise.rejects.push(erro);
// } else if (promise.status === 'FULFILLED') {
// success(promise.value);
// } else if (promise.status === 'REJECTED') {
// erro(promise.reason);
// }
// });
// };
//
//
// Promise.prototype.catch = function(onRejected){
// return this.then(null, onRejected);
// };
function getInfo(success, fail) {
return new Promise((resolve, reject) => {
setTimeout(_ => {
let ran = Math.random();
console.log(success, ran);
if (ran > 0.5) {
resolve(success);
} else {
reject(fail);
}
}, 200);
})
}
getInfo('Vchat', 'fail').then(res => {
console.log('1', res);
return getInfo('可以线上预览了', 'erro');
}).catch(err => {
console.log('2', err);
}).then(res => {
console.log('3', res);
}).catch(err => {
console.log('4', err);
});