实现
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 = undefined
failCallback = undefined
resolve = value => {
if (this.status !== PENDING) return
this.status = FULFILLED
this.value = value
this.successCallback && this.successCallback(value)
}
reject = reason => {
if (this.status !== PENDING) return
this.status = REJECTED
this.reason = reason
this.failCallback && this.failCallback(reason)
}
then(successCallback, failCallback) {
if (this.status === FULFILLED) {
successCallback(this.value)
} else if (this.status === REJECTED) {
failCallback(this.reason)
} else {
this.successCallback = successCallback
this.failCallback = failCallback
}
}
}
module.exports = MyPromise
测试
const MyPromise = require('./04-my-promise-async')
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('成功!')
}, 2000)
// reject('失败!')
})
promise.then(value => {
console.log(value)
}, reason => {
console.log(reason)
})