面试常考题之一: 手写一个Promise
本文简单实现了一个Promise

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
function myPromise (executor) {
var _this = this
this.state = 'pending'
this.value = undefined
this.reason = undefined
this.onFulfilledFunc = []
this.onRejectedFunc = []

executor(resolve, reject)
function resolve (value) {
if (_this.state === 'pending') {
_this.value = value
value && _this.onFulfilledFunc.forEach(fn => fn(value))
_this.state = 'resolved'
}
}
function reject (reason) {
if (_this.state === 'pending') {
_this.reason = reason
_this.onRejectedFunc.forEach(fn => fn(reason))
_this.state = 'rejected'
}
}
}

myPromise.prototype.then = function (onFulfilled, onRejected) {
const _this = this
if (_this.state === 'pending') {
typeof onFulfilled === 'function' && _this.onFulfilledFunc.push(() => onFulfilled(this.value))
typeof onRejected === 'function' && _this.onRejectedFunc.push(() => onRejected(this.reason))
}

return new myPromise((resolve, reject) => {
typeof onFulfilled === 'function' && resolve(onFulfilled(this.value))
typeof onRejected === 'function' && reject(onRejected(this.reason))
})
}

var p = new myPromise((resolve, reject) => {
setTimeout(() => {
resolve('aaa')
}, 500)
})

p.then(data1 => {console.log(data1);return 'bbb'})
.then(data2 => console.log(data2))