const PENDING = 'PEINDING'
const REJECTED = 'REJECTED'
const RESOLVE = 'RESOLVE'
const reslovePromise = (promise2, x, resolve, reject) => {
let then = x.then;
let called;
if (typeof then === 'function') {
then.call(x, y => { // 根据 promise 的状态决定是成功还是失败
if (called) return;
called = true;
resolvePromise(promise2, y, resolve, reject);
}, r => {
if (called) return;
called = true;
reject(r);
});
} else {
resolve(x);
}
}
Promise {
constructor (executor) {
this.status = PENGDING
this.value = null
this.reson = null
this.onRejectCallbacks = []
this.onResovlveCallBacks = []
let resolve = (value) {
if (this.staus === PENDING) {
this.status = RESOLVE
this.value = value
this.onResovleCallbacks.forEach((fn) => fn())
}
}
let reject = (reason) {
if (this.status === PENDING) {
this.staus = REJECTED
this.reason = reason
this.onRejectCallbacks.forEach((fn) => fn())
}
}
try {
executor(resolve, reject)
}catch (err){
reject(err)
}
}
then (onResolve, onReject) {
onResolve = typeOf onResolve === 'function' ? onResolve : v => v
onReject = typeOf onReject === 'function' ? onReject : err => {throw err}
// then穿透
const promise2 = new Promise(async (resolve, reject) => {
if (this.staus === RESOLVE) {
try {
let x = await onResolve(this.value)
reslovePromise(promise2,x,resolve, reject)
} catch(err) {
reject(err)
}
}
if (this.status === REJECTED) {
try {
let x = await onResolve(this.reason)
reslovePromise(promise2,x,resolve, reject)
} catch(err) {
reject(err)
}
}
if (this.status === PENDING) {
this.onResolveCallbacks.push(() => {
try {
let x = await onResolve(this.reason)
reslovePromise(promise2,x,resolve, reject)
} catch(err) {
reject(err)
}
})
this.onRejectCallbacks.push(() => {
try {
let x = await onResolve(this.reason)
reslovePromise(promise2,x,resolve, reject)
} catch(err) {
reject(err)
}
})
}
})
return promise2
}
}