经常在面试题中会看到,让你实现一个Promsie,或者问你实现Promise的原理,所以今天就尝试利用class类的形式来实现一个Promise
为了不与原生的Promise命名冲突,这里就简单命名为MyPromise.
class MyPromise {
constructor(executor) {
let _this = this
this.state = 'pending' // 当前状态
this.value = undefined // 存储成功的值
this.reason = undefined // 存储失败的值
// 利用发布订阅模式,让Promise支持异步
this.onFulfilledFunc = [] // 存储成功的回调
this.onRejectedFunc = [] // 存储失败的回调
function resolve (value) {
// Promise对象已经由pending状态改变为了成功态(resolved)或是失败态(rejected)就不能再次更改状态了。因此我们在更新状态时要判断,如果当前状态是pending(等待态)才可更新
if (_this.state === 'pending') {
_this.value = value
//依次执行成功回调
_this.onFulfilledFunc.forEach(fn => fn(value))
_this.state = 'resolved'
}
}
function reject (reason) {
// Promise对象已经由pending状态改变为了成功态(resolved)或是失败态(rejected)就不能再次更改状态了。因此我们在更新状态时要判断,如果当前状态是pending(等待态)才可更新
if (_this.state === 'pending') {
_this.reason = reason
//依次执行失败回调
_this.onRejectedFunc.forEach(fn => fn(reason))
_this.state = 'rejected'
}
}
try {
// 当实例化Promise时,构造函数中就要马上调用传入的executor函数执行
executor(resolve, reject)
} catch (error) {
reject(error)
}
}
_resolvePromise (promise2, x, resolve, reject) {
// 如果返回了自己的Promise对象,状态永远为等待态(pending),再也无法成为resolved或是rejected,程序会死掉,因此首先要处理它
if (promise2 === x) {
reject(new TypeError('Promise存在循环引用'))
}
if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
// x可能是一个promise
try {
let then = x.then
if (typeof then === 'function') {
then.call(x, (y) => {
_resolvePromise(promise2, y, resolve, reject)
})
} else {
resolve(x)
}
} catch (err) {
reject(err)
}
} else {
//否则是个普通值
resolve(x)
}
}
then (onFulfilled, onRejected) {
let promise2
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : function (val) { return val }
onRejected = typeof onRejected === 'function' ? onRejected : function (reason) { throw reason }
if (this.state === 'resolved') {
promise2 = new MyPromise((resolve, reject) => {
setTimeout(() => {
try {
let x = onFulfilled(this.value)
this._resolvePromise(promise2, x, resolve, reject)
} catch (error) {
reject(error)
}
}, 0);
})
}
if (this.state === 'rejected') {
promise2 = new MyPromise((resolve, reject) => {
setTimeout(() => {
try {
let x = onRejected(this.reason)
this._resolvePromise(promise2, x, resolve, reject)
} catch (error) {
reject(error)
}
}, 0);
})
}
if (this.state === 'pending') {
promise2 = new MyPromise((resolve, reject) => {
this.onFulfilledFunc.push(() => {
setTimeout(() => {
try {
let x = onFulfilled(this.value)
this._resolvePromise(promise2, x, resolve, reject)
} catch (error) {
reject(error)
}
}, 0);
})
this.onRejectedFunc.push(() => {
setTimeout(() => {
try {
let x = onRejected(this.reason)
this._resolvePromise(promise2, x, resolve, reject)
} catch (error) {
reject(error)
}
}, 0);
})
})
}
return promise2
}
}
运行测试:
var promise = new MyPromise((resolve, reject) => {
console.log(1)
setTimeout(() => {
resolve(2)
}, 1000);
console.log(3)
}).then(value => console.log(value))
结果真香: