class MyPromise {
// 三种状态
static PENDING = 'pending'
static FULFILLED = 'fulfilled'
static REJECTED = 'rejected'
constructor(exector) {
this.status = MyPromise.PENDING
this.result = null
this.fulfilledCbs = []
this.rejectedCbs = []
const resolve = (value) => {
if (this.status !== MyPromise.PENDING) return
this.status = MyPromise.FULFILLED
this.result = value
while(this.fulfilledCbs.length) {
const cb = this.fulfilledCbs.shift()
cb()
}
}
const reject = (err) => {
if (this.status !== MyPromise.PENDING) return
this.status = MyPromise.REJECTED
this.result = err
while(this.rejectedCbs.length) {
const cb = this.rejectedCbs.shift()
cb()
}
}
exector(resolve, reject)
}
then(onFulfilled, onRejected) {
return new MyPromise((resolve, reject) => {
const handleFulfilled = () => {
const res = onFulfilled(this.result)
if (res instanceof MyPromise) {
res.then(resolve, reject)
} else {
resolve(res)
}
}
const handleRejected= () => {
const err = onRejected(this.result)
if (err instanceof MyPromise) {
err.then(resolve, reject)
} else {
resolve(err)
}
}
if (this.status === MyPromise.FULFILLED) {
handleFulfilled()
} else if (this.status === MyPromise.REJECTED) {
handleRejected()
} else {
onFulfilled && this.fulfilledCbs.push(handleFulfilled)
onRejected && this.rejectedCbs.push(handleRejected)
}
})
}
catch(onRejected) {
return this.then(null, onRejected)
}
}
const p = new MyPromise(resolve => resolve(1))
p.then(v => {
console.log(v)
return 100
}).then(v2 => {
console.log(v2) // 100
})
p.then(v => {
return new MyPromise(r => r(200))
}).then(v3 => {
console.log(v3) //200
})
// 同一个promise多次then,互不影响
p.then(v => console.log('p1', v))
p.then(v => console.log('p2', v))
console