const PEDDING = 'PEDDING';
const RESOLVE = 'RESOLVE';
const REJECT = 'REJECT';
// promise 有三种状态
class NewPromise {
// 初始状态为 PEDDING
status = PEDDING
result = undefined;
reason = undefined;
// 公布订阅者模式
// 目标是为了实现异步
onResolveArr = [];
onRejectArr = [];
constructor(exc) {
const resolve = result => {if (this.status === PEDDING) {
this.result = result
this.status = RESOLVE
// 执行订阅者
this.onResolveArr.map(fn => fn())
}
}
const reject = reason => {if (this.status === PEDDING) {
this.reason = reason
this.status = REJECT
// 执行订阅者
this.onRejectArr.map(fn => fn())
}
}
exc(resolve, reject)
}
then(onResolve, onReject) {if (this.status === RESOLVE) {setTimeout(() => {onResolve(this.result)
}, 0)
}
if (this.status === REJECT) {setTimeout(() => {onReject(this.reason)
}, 0)
}
// 公布订阅者模式
if (this.status === PEDDING) {
// 将发布者增加到数组外面
this.onResolveArr.push(() => {onResolve(this.result)
})
this.onRejectArr.push(() => {this.onReject(this.reason)
})
}
}
}
// let yan = new Promise((resole, reject) => {// resole('闫大爷真帅')
// })
// yan.then(res => {// console.log(res)
// })
let newYan = new NewPromise((resole, reject) => {setTimeout(()=>{resole('new 闫大爷真帅')
},3000)
})
newYan.then(res => {console.log(res)
})
console.log(11111111)