手写简易Promise

// 定义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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值