实现一个简易版 Promise
const PENDINGS='pending'
const RESOLVEDS='resolved'
cosnt REJECTED='rejected'
function promise(fn){
const _this=this;
_this.state=PENDINGS
_this.vaule=null
_this.resolvedCallbacks = []
_this.rejectedCallbacks = []
//还没有完善代码
//在这里创建了三个常量用于表示状态
//因为函数可能会异步执行,所以先使用中间变量获取this对象
//1.pending 2.vaule用于保存resolve 或者reject中传入的值
//resolvedCallbacks 和 rejectedCallbacks 用于保存 then 中的回调函数
//在这里开始完善代码
function resolve(value) {
if (_this.state === PENDING) {
_this.state = RESOLVED
_this.value = value
_this.resolvedCallbacks.map(cb => cb(_this.value))
}
}
function reject(value) {
if (_this.state === PENDING) {
_this.state = REJECTED
_this.value = value
_this.rejectedCallbacks.map(cb => cb(_this.value))
}
}
}
//完成以上两个函数以后,我们就该实现如何执行 Promise 中传入的函数了
try {
fn(resolve, reject)
} catch (e) {
reject(e)
}