CY

使生如夏花之绚烂,死如秋叶之静美

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
class P {
constructor(exector) {
if (typeof exector !== 'function')
throw TypeError(`Promise resolver ${arguments[0]} is not a function`)

this.status = 'pending'
this.value = null
this.resolveList = []
this.rejectList = []

try {
exector(this._resolve.bind(this), this._reject.bind(this))
} catch (e) {
this._reject(e)
throw e
}
}

_resolve(value) {
if (this.status === 'pending') {
this.value = value
if (value instanceof P) {
value.then(value => {
this.value = value
})
}
this.status = 'fulfilled'
setTimeout(() => {
this.resolveList.forEach(resolve => {
resolve(this.value)
this.resolveList.shift()
})
}, 0)
}
}

_reject(value) {
// console.log(value)
if (this.status === 'pending') {
this.status = 'rejected'
this.value = value
this.rejectList.forEach(reject => {
reject(this.value)
this.rejectList.shift()
})
}
}

then(resolveFn, rejectFn) {
resolveFn = typeof resolveFn === 'function' ? resolveFn : value => value
rejectFn = typeof rejectFn === 'function' ? rejectFn : value => value

if (this.status === 'fulfilled') {
return new P((resolve, reject) => {
const result = resolveFn(this.value)
if (result instanceof P) result.then(resolve, reject)
resolve(result)
})
}

if (this.status === 'rejected') {
return new P((resolve, reject) => {
const result = rejectFn(this.value)
if (result instanceof P) result.then(resolve, reject)
reject(result)
})
}

if (this.status === 'pending') {
return new P((resolve, reject) => {
this.resolveList.push(() => {
try {
const result = resolveFn(this.value)
resolve(result)
} catch (e) {
reject(e)
}
})

this.rejectList.push(() => {
try {
const result = rejectFn(this.value)
resolve(result)
} catch (e) {
reject(e)
}
})
})
}
}

static resolve(value) {
if (value instanceof P) return value
return new P(resolve => resolve(value))
}

static reject(value) {
return new P((resolve, reject) => reject(value))
}

catch(rejectFn) {
return this.then(undefined, rejectFn)
}
}

new P((resolve, reject) => {
setTimeout(() => reject('init'), 1000)
})
.then(data => {
console.log(data)
return 'first'
})
.then(data => {
console.log(data)
return 'second'
})
.then(data => {
console.log(data)
})```

本文作者 : CY
本文使用 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议
本文链接 : https://runtua.cn/2019/05/30/promise/

本文最后更新于 天前,文中所描述的信息可能已发生改变