手写Promise核心代码

2022-05-07  本文已影响0人  江火渔枫
const { reject } = require("core-js/fn/promise");

class Commitment {

    static PENDING = '待定';
    static FULFILLED = '成功';
    static REJECTED = '拒绝';

    constructor(func){
        this.status = Commitment.PENDING;
        this.result = null;
        this.resolveCallbacks = [];
        this.rejectCallbacks = [];
        //***bind(this) 将this指向新创建的对象 commitment ****/
        //func(this.resolve.bind(this), this.reject.bind(this));

        //原生promise调用than 可以把错误的信息做为内容输出出来 调用方式如下
        /***
         * let promise = new Promise((resolve, reject) => {
         *  throw new Error('输出错误信息');
         * })
         * ** */
        try{
            func(this.resolve.bind(this), this.reject.bind(this));
        } catch (error){
            //这里是直接执行不是创建实例后再执行 不用绑定this
            this.reject(error);
        }
    }

    resolve(){
        setTimeout(() => {
            if(this.status === Commitment.PENDING){
                this.status = Commitment.FULFILLED;
                this.result = result;
                this.resolveCallbacks.forEach(callback =>{
                    callback(result)
                })
            }
        });
    }
    reject(){
        setTimeout(() => {
            if(this.status === Commitment.PENDING){
                this.status = Commitment.REJECTED;
                this.result = result;
                this.rejectCallbacks.forEach(callback => {
                    callback(result)
                })
            }
        });
    }
    than(onFULFILLED, onREJECTED){
        //为实现 .than链式调用  方法内返回new Commitment
        return new Commitment((resolve, reject) => {
            // than 里面的两个参数不是函数则不被执行
            //解决思路 赋值空函数
            onFULFILLED = typeof onFULFILLED === 'function' ? onFULFILLED : () => {};
            onREJECTED = typeof onREJECTED === 'function' ? onREJECTED : () => {};
            if(this.status === Commitment.PENDING){
                this.resolveCallbacks.push(onFULFILLED);
                this.rejectCallbacks.push(onREJECTED);
            }
            if(this.status === Commitment.FULFILLED){
                onFULFILLED(this.result);
            }
            if(this.status === Commitment.REJECTED){
                onREJECTED(this.result);
            }
        })
    }
}

let commitment = new Commitment((resolve, reject) => {
    resolve('这次一定');
});
commitment.than(
    result => {console.log(result)},
    result => {console.log(result.message)}
).than(
    result => {console.log(result)},
    result => {console.log(result.message)}
);

代码执行流程图

https://www.bilibili.com/video/BV1RR4y1p7my?spm_id_from=333.337.search-card.all.click

上一篇下一篇

猜你喜欢

热点阅读