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)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。