// 定义promise的三个状态
const PENDING = "PENDING"
const RESOLVED = "RESOLVED"
const REJECTED = "REJECTED"
function myPromsie(fn) {
// 保存当前执行上下文
let _this = this
// 初始状态是pending
this.status = PENDING
// 参数
this.params = null
// 、定义两个回调数组:存储resolve 和 reject 要执行的函数(then传进来的函数)
this.resolvedCallbacks = []
this.rejectedCallbacks = []
// 定义resolve函数
function resolve(params) {
// 状态为PENDING时才操作
if (_this.status == PENDING) {
// 修改状态
_this.status = RESOLVED
_this.params = params
// 遍历执行函数
_this.resolvedCallbacks.map((cb) => cb(_this.params))
}
}
// 定义reject函数
function reject(params) {
// 状态为PENDING时才操作
if (_this.status == PENDING) {
// 修改状态
_this.status = REJECTED
_this.params = params
// 遍历执行函数
_this.rejectedCallbacks.map(cb => cb(_this.params));
}
}
// 执行参数函数fn()
try {
fn(resolve, reject)
} catch (err) {
reject(err)
}
}
// 通过then实现链式调用
myPromsie.prototype.then = function (onFulfilled, onRejected) {
let _this = this
// 当状态为PENDING时,把onFulfilled 和 onRejected 加进对应数组当中
if (_this.status == PENDING) {
_this.resolvedCallbacks.push(onFulfilled)
_this.rejectedCallbacks.push(onRejected)
}
// 当状态为 RESOLVED 时 , 执行 onFulfilled
if (_this.status == RESOLVED) return onFulfilled(_this.params)
// 当状态为 REJECTED 时 , 执行 onRejected
if (_this.status == REJECTED) return onRejected(_this.params)
}
// 测试
let a = new myPromsie((resolve, reject) => {
resolve({ a: 1, b: 2, c: 3 })
// reject("cccc")
})
a.then(res => {
console.log(res, 1111);
}, err => {
console.log(err, 2222);
})
console.log(a);
手写简易Promise
最新推荐文章于 2024-06-13 02:48:16 发布