其他分享
首页 > 其他分享> > 手写Promise (2)实现then方法

手写Promise (2)实现then方法

作者:互联网

class MyPromise {
    constructor(executor) {
        this.state = 'pending';
        this.value = null;
        try {
              executor(this.resolve.bind(this),this.reject.bind(this));
        } catch(error) {
            this.reject(error)
        }
    }
    resolve(value) {
        if(this.state === 'pending') {
            this.state = 'fulfilled';
            this.value = value;
        }
        
    }
    reject(value) {
        if(this.state = 'pending') {
            this.state = 'rejected';
            this.value = value;
        }
    }

    then(onFulfilled,onRejected) {
        // 解决参数未传入函数的情况
        if(typeof onFulfilled !== 'function') {
            onFulfilled = value => value;
        }
        if(typeof onRejected !== 'function') {
            onRejected = value => value;
        }
        if(this.state === 'fulfilled') {
            // 使代码异步执行
             setTimeout(() => {
                try {
                    onFulfilled(this.value)
                }catch(error) {
                    this.reject(error)
                }
             });
            
        }
        if(this.state === 'rejected') {
            setTimeout(() => {
                try {
                    onRejected(this.value)
                }catch(error) {
                    this.reject(error)
                }
            });
        }
    }
}

 

标签:reject,value,onFulfilled,state,Promise,error,手写,onRejected,方法
来源: https://www.cnblogs.com/jmh0113/p/14615689.html