码迷,mamicode.com
首页 > 其他好文 > 详细

手写Promise (2)实现then方法

时间:2021-04-06 14:22:04      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:struct   nbsp   time   bind   异步执行   led   The   bsp   class   

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

 

手写Promise (2)实现then方法

标签:struct   nbsp   time   bind   异步执行   led   The   bsp   class   

原文地址:https://www.cnblogs.com/jmh0113/p/14615689.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!