-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromise.ts
More file actions
128 lines (108 loc) · 2.47 KB
/
promise.ts
File metadata and controls
128 lines (108 loc) · 2.47 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
class MyPromise {
status: 'fulfilled' | 'pending' | 'rejected';
result = null
error = null
onFulfilledList = []
onRejectedList = []
constructor(fn) {
this.status = 'pending';
let ctx = this;
let resolve = (data) => {
// 多次resolve无效
if (ctx.status !== 'pending') {
return;
}
ctx.status = 'fulfilled';
ctx.result = data;
ctx.onFulfilledList.forEach(onFulfilled => {
setTimeout(() => {
onFulfilled(data)
}, 0)
});
}
let reject = (err) => {
if (ctx.status !== 'pending') {
return;
}
ctx.status = 'rejected';
ctx.error = err;
ctx.onRejectedList.forEach(onRejected => {
setTimeout(() => {
onRejected(err)
}, 0)
});
}
try {
fn.call(this, resolve, reject)
} catch (e) {
reject(e)
}
}
then(onFulfilled, onRejected?) {
if (this.status === 'fulfilled') {
onFulfilled(this.result)
return MyPromise.resolve(this.result);
}
if (this.status === 'rejected') {
if (onRejected) {
onRejected(this.error)
}
return MyPromise.reject(this.error)
}
if (this.status === 'pending') {
let ctx = this;
const newPromise = new MyPromise((resolve, reject) => {
ctx.onFulfilledList.push((result) => {
try {
const res = onFulfilled(result);
resolve(res);
} catch (e) {
reject(e)
}
})
ctx.onRejectedList.push((reason) => {
try {
resolve(onRejected(reason))
} catch {
reject(reason)
}
})
})
return newPromise;
}
}
catch(onRejected) {
return this.then(null, onRejected)
}
static resolve(p) {
return new MyPromise((resolve) => {
resolve(p)
})
}
static reject(e) {
return new MyPromise((resolve, reject) => {
reject(e)
})
}
}
let p = new MyPromise((resolve) => {
setTimeout(() => {
console.log('ee')
resolve('ee')
}, 1000);
})
let p1 = p.then((res) => {
console.log(4, res)
return 'w4'
})
let p2 = p1.then((res) => {
console.log(5, res)
throw 'wrong'
return 'w5'
})
let p3 = p2.then((res) => {
console.log(6, res)
return 'w6'
}, (e) => { console.log('hold', e); return 'catched' })
p3.then((res) => { console.log(7, res) }, (e) => { console.log('reject', e, p3) })
setTimeout(() => console.log(p, p1, p2, p3), 3000)