自己实现一个简易的promise


    const PENDING = 'pending'
    const RESOLVED = 'resolved'
    const REJECTED = 'rejected'

    function MyPromise(fn) {
        let that = this
        that.state = PENDING
        that.value = undefined
        //存储成功状态的回调函数
        that.resolvedList = []
        //存储失败状态的回调函数
        that.rejectedList = []

        //立即执行Promise中的函数fn,fn接受resolve和reject函数作为参数
        fn(resolve,reject)

        function resolve(x) {
            that.state = RESOLVED
            that.value = x
            //new Promise实例化后去调用then()方法,如果promise对象的状态还是pending,
            // 会先把对应的回调函数存储到resolvedList、rejectedList数组中,
            //等到执行resolve的时候,去对应的数组中找到要执行的回调函数,把resolve传的值传递给回调函数
            if (that.resolvedList.length != 0){
                that.resolvedList.forEach(function (fn,index) {
                    fn(that.value)
                })
            }

        }

        function reject(x) {
            that.state = REJECTED
            that.value = x
            if (that.rejectedList.length != 0){
                that.rejectedList.forEach(function (fn,index) {
                    fn(that.value)
                })
            }
        }
    }

    MyPromise.prototype.then = function (fn1,fn2) {

        let that = this

        //判断fn1/2是否是函数类型
        fn1 = typeof fn1 == 'function'? fn1:(msg)=>console.log(msg)
        fn2 = typeof fn2 == 'function'? fn2:(err)=>console.log(err)

        //new Promise实例化后,状态没有改变,就预先把回调函数存到对应的数组中,
        // 待到执行resolve或者reject函数的时候,去对应数组中找回调函数
        if (that.state == PENDING){
            that.resolvedList.push(fn1)
            that.rejectedList.push(fn2)
        }

        //new Promise实例化后,状态为成功状态,调用then()方法就直接执行回调函数,并返回新的promise对象
        if (that.state == RESOLVED){
            let res = fn1(that.value)
            if(res instanceof MyPromise){
                return res
            }else {
                return new MyPromise(function (resolve,reject) {
                    resolve()
                })
            }
        }

        if (that.state == REJECTED){
            let res = fn2(that.value)
            if(res instanceof MyPromise){
                return res
            }else {
                return new MyPromise(function (resolve,reject) {
                    resolve()
                })
            }
        }
    }

    let promise = new MyPromise(function (res,rej) {
        setTimeout(res,3000,789)
        console.log(123)
    })

    promise.then(msg=>console.log(msg))
    console.log(promise)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值