class MyPromise {
constructor(executor) {
this.initValue()
this.initBind()
try {
executor(this.resolve, this.reject)
} catch (e) {
this.reject(e)
}
}
initBind() {
this.resolve = this.resolve.bind(this)
this.reject = this.reject.bind(this)
}
initValue() {
this.PromiseResult = null
this.PromiseState = 'pending'
this.onFulfilledCallbacks = []
this.onRejectedCallbacks = []
}
resolve(value) {
if(this.PromiseState !== 'pending') {
return
}
this.PromiseState = 'fulfilled'
this.PromiseResult = value
while(this.onFulfilledCallbacks.length) {
this.onFulfilledCallbacks.shift()(this.PromiseResult)
}
}
reject(reason) {
if(this.PromiseState !== 'pending') {
return
}
this.PromiseState = 'rejected'
this.PromiseResult = reason
while(this.onRejectedCallbacks.length) {
this.onRejectedCallbacks.shift()(this.PromiseResult)
}
}
then_old(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : val => val
onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason }
if (this.PromiseState === 'fulfilled') {
onFulfilled(this.PromiseResult)
} else if (this.PromiseState === 'rejected') {
onRejected(this.PromiseResult)
} else if (this.PromiseState === 'pending') {
this.onFulfilledCallbacks.push(onFulfilled.bind(this))
this.onRejectedCallbacks.push(onRejected.bind(this))
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : val => val
onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason }
var thenPromise = new MyPromise((resolve, reject) => {
const resolvePromise = cb => {
try {
const x = cb(this.PromiseResult)
if (x === thenPromise) {
throw new Error('不能返回自身')
}
if (x instanceof MyPromise) {
x.then(resolve, reject)
} else {
resolve(x)
}
} catch (err) {
reject(err)
throw new Error(err)
}
}
if (this.PromiseState === 'fulfilled') {
resolvePromise(onFulfilled)
} else if (this.PromiseState === 'rejected') {
resolvePromise(onRejected)
} else if (this.PromiseState === 'pending') {
this.onFulfilledCallbacks.push(resolvePromise.bind(this, onFulfilled))
this.onRejectedCallbacks.push(resolvePromise.bind(this, onRejected))
}
})
return thenPromise
}
}
const promise = new MyPromise((resolve, reject) => {
resolve('success')
})
const p1 = promise.then(value => {
console.log(1)
console.log('resolve', value)
return p1
})
p1.then(value => {
console.log(2)
console.log('resolve', value)
}, reason => {
console.log(3)
console.log(reason.message)
})
console