实现
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
while(this.successCallback.length) this.successCallback.shift()(value)
}
reject = reason => {
if (this.status !== PENDING) return
this.status = REJECTED
this.reason = reason
while(this.failCallback.length) this.failCallback.shift()(reason)
}
then(successCallback, failCallback) {
if (this.status === FULFILLED) {
successCallback(this.value)
} else if (this.status === REJECTED) {
failCallback(this.reason)
} else {
this.successCallback.push(successCallback)
this.failCallback.push(failCallback)
}
}
}
module.exports = MyPromise
测试
const MyPromise = require('./05-my-promise-multiple')
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('成功!')
}, 2000)
// reject('失败!')
})
promise.then(value => {
console.log(111111, value)
}, reason => {
console.log(222222, reason)
})
promise.then(value => {
console.log(333333, value)
}, reason => {
console.log(444444, reason)
})
promise.then(value => {
console.log(555555, value)
}, reason => {
console.log(666666, reason)
})