const PENDING = 'pending' // 等待
const FULFILLED = 'fulfilled' // 成功
const REJECTED = 'rejected'// 失败
class MyPromise {
constructor(executor) {
executor(this.resolve, this.reject)
}
status = PENDING
value = undefined
reason = undefined
successCallback = []
failCallback = []
resolve = value => {
if (this.status !== PENDING) return
// 将状态修改为成功
this.status = FULFILLED
// 保存成功之后的值
this.value = value
// this.successCallback && this.successCallback(this.value)
while(this.successCallback.length) {
this.successCallback.shift()(this.value)
}
}
reject = reason => {
if (this.status !== PENDING) return
this.status = REJECTED
this.reason = reason
// this.failCallback && this.failCallback(this.reason)
while(this.failCallback.length) {
this.failCallback.shift()(this.reason)
}
}
then(successCallback, failCallback) {
let promise2 = new MyPromise((resolve, reject) => {
if (this.status === FULFILLED) {
setTimeout(() => {
let x = successCallback(this.value)
// resolve(x)
resolvePromise(promise2, x, resolve, reject)
}, 0)
} else if (this.status === REJECTED) {
failCallback(this.reason)
} else {
// 等待
// 讲成功回调和失败回调进行存储
this.successCallback.push(successCallback)
this.failCallback.push(failCallback)
}
})
return promise2
}
}
function resolvePromise(promise2, x, resolve, reject) {
if (promise2 === x) {
return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
}
if (x instanceof MyPromise) {
// x.then(value => resolve(value), reason => reject(reason))
x.then(resolve, reject)
} else {
resolve(x)
}
}
module.exports = MyPromise
let pro = new MyPromise((resolve, reject) => {
resolve('hello')
})
let p = pro.then((value) => {
return p;
})
p.then((val) => {}, reason => {
console.log(reason)
})
网友评论