手写promies

<script>
    function myPromise(excutor) {
        let self = this
        self.status = 'pending'
        self.value = null
        self.reason = null

        self.onFulfilledCallbacks = []
        self.onRejectedCallbacks = []

        function resolve(value) {
            console.log(this); //this 是window
            if (self.status === 'pending') {
                self.value = value
                self.status = 'fulfiled'
                self.onFulfilledCallbacks.forEach((item) => {
                    item(value)
                })
            }
        }

        function reject(reason) {
            if (self.status === 'pending') {
                self.reason = reason
                self.status = 'rejected'
                self.onRejectedCallbacks.forEach((item) => {
                    item(reason)
                })
            }
        }
        excutor(resolve, reject)
    }
    myPromise.prototype.then = function (
        onFulfilled, onRejected
    ) {
        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : function (data) {
            resolve(data)
        }
        onRejected = typeof onRejected === 'function' ? onRejected : function (data) {
            reject(data)
        }
        // onFulfilled()
        console.log(this.status);
        //若果是pending状态我就不执行,先存起来
        if (this.status === 'pending') {
            this.onFulfilledCallbacks.push(onFulfilled)
            this.onRejectedCallbacks.push(onRejected)

        }
        // if (this.status === 'pending') {

        // }
    }
    let demo = new myPromise((resolve, reject) => {
        setTimeout(() => {
            resolve(3)
        }, 1);
        // resolve(3)

    }).then((res) => {
        console.log(res, 0000);
        console.log(1);
    })

    // function B() {
    //     function c() {
    //         console.log(1);
    //     }
    // }
    // B.prototype.test = function () {
    //     c()
    // }
    // let tao = new B()
    // tao.test()
</script>

要点,因为是异步 。then()的时候 reslove的状态并没有改变

其实在时间线上,then()会比reslove() 先执行

所以在。then()判断是否为pending,若果是pending就挂起来,在reslove的时候再去取

reslove function 中的this是

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值