Promise的简易版本,未实现链式和catch,仅限于理解原理
class Promise {
constructor(executor) {
this.state = 'pending'
this.value = undefined
this.reason = undefined
this.onFulfilledCallbacks = []
this.onRejectedCallbacks = []
const resolve = (value) => {
if (this.state !== 'pending') {
return
}
this.state = 'fulfilled'
this.value = value
this.onFulfilledCallbacks.forEach(callback => callback(this.value))
}
const reject = (reason) => {
if (this.state !== 'pending') {
return
}
this.state = 'rejected'
this.reason = reason
this.onRejectedCallbacks.forEach(callback => callback(this.reason))
}
executor(resolve, reject)
}
then(onFulfilled, onRejected) {
if (this.state === 'pending') {
this.onFulfilledCallbacks.push(() => onFulfilled(this.value))
this.onRejectedCallbacks.push(() => onRejected(this.reason))
} else if (this.state === 'fulfilled') {
onFulfilled(this.value)
} else if (this.state === 'rejected') {
onRejected(this.reason)
}
}
}
// 测试代码
const p = new Promise((resolve, reject) => {
console.log('executor')
// resolve('succ')
// reject('error')
// setTimeout(() => {
// resolve("succ")
// }, 1000)
setTimeout(() => {
reject("error")
}, 1000)
})
p.then(value => {
console.log('resolve 1:', value)
}, reason => {
console.log('reject 1:', reason)
})
p.then(value => {
console.log('resolve 2:', value)
}, reason => {
console.log('reject 2:', reason)
})
p.then(value => {
console.log('resolve 3:', value)
}, reason => {
console.log('reject 3:', reason)
})
console.log('end')