手写promise源代码雏形

class valiPromise {
    constructor(fn) {
        this.status = 'pending';
        this.resolveFnArr = [];
        this.rejectFnArr = [];
        let resolve = (data) => {
            if (this.status === 'pending') {
                this.data = data;
                this.resolveFnArr.map(item => {
                    item();
                })
                this.status = 'fullFilled'
            }

        }
        let reject = (data) => {
            if (this.status === 'pending') {
                this.data = data;
                this.rejectFnArr.map(item => {
                    item();
                })
                this.status = 'rejected';
            }
        }
        try {
            fn(resolve, reject)
        } catch (error) {
            reject(error)
        }

    }

    then(fullFilledFn, rejectedFn) {
        // console.log('then   :   ', this.status, 'status', this.data, 'this.data', typeof fullFilledFn, typeof rejectedFn)
        if (this.status === 'fullFilled' && typeof fullFilledFn === 'function') {
            fullFilledFn(this.data)
        }

        if (this.status === 'rejected' && typeof rejectedFn === 'function') {
            rejectedFn(this.data)
        }
        // handle async code  when async will run then code first and because this.status equal pending up code don't run
        if (this.status === 'pending') {
            this.resolveFnArr.push(() => {
                fullFilledFn(this.data)
            })
            this.rejectFnArr.push(
                () => {
                    rejectedFn(this.data)
                }
            )


        }


        // 链式调用
        return this
    }
}

function testPromise() {
    return new valiPromise(function (resolve, reject) {
        setTimeout(() => {
            resolve(1000)
        }, 2000);
    })
}

function testPromise1() {
    return new valiPromise(function (resolve, reject) {
        setTimeout(() => {
            resolve(2000)
        }, 2000);
    })
}
testPromise().then((data) => {
    console.log(data);
    testPromise1().then((data) => console.log(data))
})

有参考下面链接
https://www.cnblogs.com/xinggood/p/11836096.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值