class myPromise{
static PENDING = 'pending'
static FULLFILLED = 'resolved'
static REJECTED = 'rejected'
constructor (executor) {
this.status = myPromise.PENDING
this.value = undefined
this.reason = undefined
// 成功时的回调
this.onResolvedCbs = []
// 失败时的回调
this.onRejectedCbs = []
const resolve = (value) => {
if (this.status === myPromise.PENDING) {
this.status = myPromise.FULLFILLED
this.value = value
this.onResolvedCbs.forEach(fun => fun.call())
}
}
const reject = (error) => {
if (this.status === myPromise.PENDING) {
this.status = myPromise.REJECTED
this.reason = error
this.onRejectedCbs.forEach(fun => fun())
}
}
try{
executor(resolve, reject)
} catch (e) {
reject(e)
}
}
then (onFulFilled = function () {}, onRejected = function () {}) {
console.log(this)
let value = this.value
// 根据Promise实例状态决定then的执行
return new myPromise((resolve, reject) => {
let value
if (this.status === myPromise.PENDING) {
this.onResolvedCbs.push(() => {
setTimeout(() => {
try {
value = onFulFilled(this.value) || value
resolve(value)
} catch (e) {
reject(e)
}
})
})
this.onRejectedCbs.push(() => {
setTimeout(() => {
try {
value = onRejected(this.reason)
resolve(value || lastValue)
} catch (e) {
reject(e)
}
})
})
} else if (this.status === myPromise.FULLFILLED) {
setTimeout(() => {
try {
value = onFulFilled(this.value) || value
resolve(value)
} catch (e) {
reject(e)
}
})
} else {
try {
onRejected(this.reason)
} catch (e) {
reject(e)
}
}
})
}
}
const p = new myPromise((resolve, reject) => {
resolve('hello')
}).then().then((value) => {
console.log(value)
return 'hi'
}).then(val => console.log(val), err => console.log(err.toString()))
console