手写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)
                }
            });
        }
    }
}

 

相关文章

最后的控制台返回空数组.控制台在ids.map函数完成之前运行va...
我正在尝试将rxJava与我已经知道的内容联系起来,特别是来自J...
config.jsconstconfig={base_url_api:"https://douban....
我正在阅读MDN中的javascript,并且遇到了这个谈论承诺并且不...
config.jsconstconfig={base_url_api:"https://douban....
这是我的代码main.cpp:#include<string>#include<...