// 创建一个 Promise 的类
class Promise {
constructor(executer) {
// 构造函数 constructor 里面是个执行器
this.status = 'pending' // 默认的状态 pending
this.value = undefined // 成功的值默认 undefined
this.reason = undefined // 失败的值默认 undefined
// 状态只有在 pending 时候才能改变
const resolveFn = value => {
// 判断只有等待时才能 resolve 成功
if (this.status == pending) {
this.status = 'resolve'
this.value = value
}
}
// 判断只有等待时才能 reject 失败
const rejectFn = reason => {
if (this.status == pending) {
this.status = 'reject'
this.reason = reason
}
}
try {
// 把 resolve 和 reject 两个函数传给执行器 executer
executer(resolve, reject)
} catch (e) {
reject(e) // 失败的话进 catch
}
}
then(onFufilled, onReject) {
// 如果状态成功调用 onFufilled
if ((this.status = 'resolve')) {
onFufilled(this.value)
} // 如果状态失败调用 onReject
if ((this.status = 'reject')) {
onReject(this.reason)
}
}
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交