class Promise1 {
constructor(excutor) {
this.status = 'PENDING'
this.value = undefined
this.onFulfilledCallback = []
this.onRejectedCallback = []
const resolve = value => {
setTimeout(() => {
if (this.status === 'PENDING') {
this.status = 'FULFILLED'
this.value = value
this.onFulfilledCallback.forEach(fn => fn())
}
})
}
const reject = err => {
setTimeout(() => {
if (this.status === 'PENDING') {
this.status = 'REJECTED'
this.value = err
this.onRejectedCallback.forEach(fn => fn())
}
})
}
excutor(resolve, reject)
}
then(onFulfilled, onRejected) {
const self = this
const status = this.status
return new Promise1((resolve, reject) => {
if (status === 'FULFILLED') {
const value = onFulfilled(self.value)
if (value === null) return null
if (typeof value === 'object' || typeof value === 'function') {
if (typeof value.then === 'function') {
value.then(resolve, reject)
} else {
resolve(value)
}
} else { // 普通值
resolve(value)
}
} else if (status === 'REJECTED') {
const value = onRejected(self.value)
resolve(rejectedVal)
} else if (status === 'PENDING') {
self.onFulfilledCallback.push(() => {
const fulfilledVal = onFulfilled(self.value)
resolve(fulfilledVal)
})
self.onRejectedCallback.push(() => {
const rejectedVal = onRejected(self.value)
resolve(rejectedVal)
})
}
})
}
}
console.log('start')
setTimeout(() => {
console.log('setTimeout')
})
const p = new Promise1((resolve, reject) => {
resolve(1)
})
p.then(res => {
console.log('第一个then:', res)
return new Promise1((resolve, reject) => {
resolve('return Promise')
})
}).then(res => {
console.log('第二个then:', JSON.stringify(res))
return {
then(resolve, reject) {
resolve(22)
}
}
}).then(res => {
console.log('第三个then:', res)
})
console.log('end')
console