笔记-Promise

129 阅读1分钟

promise主要解决的应该是同步异步问题,是一种解决方案,常见的是接口返回后需要执行的一些方法。同时,因为promise.then的方法,解决掉了回调地狱的问题。

promise 有三种状态,执行中、成功、失败(panding,resolved,rejected)。

简单的Pomise的实现(只支持异步 & 链式调用,没有reject)

let PENDING = 'pending',
    FULFILLED = 'fulfilled';

class Promise {
    constructor(executor) {
        //初始化变量
        this.initData()
        //改变this
        this.initThis();
        //回调resolve
        executor(this.resolve);
    };
    initData() {
        this.value = null;
        this.state = 'pending';
        //延迟执行会puse这个数组 等状态改变了在执行
        this.onFulfulledArr = [];
    };
    initThis() {
        this.resolve = this.resolve.bind(this);
    };
    resolve(value) {
        if(this.state === PENDING) {
            this.state = FULFILLED;
            this.value = value;
    
            this.onFulfulledArr.forEach((fn) => fn(value))
        }  
    };
    then(onFulfulled) {
        //then 放方法的执行,肯定需要返回 promise
        let p2 = new Promise((resolve) => {
            //同步执行
            if(this.state === FULFILLED) {
               let x = onFulfulled(this.value);
               resolve(x);
            }
            //异步执行
            if(this.state === PENDING) {
                let p2 = new Promise((resolve) => {
                    //存储一个函数,在 resovle 后执行
                    this.onFulfulledArr.push(() => {
                        let x = onFulfulled(this.value);
                        resolve(x)
                    });
                })
                
            }
        });
        return p2;
    }
}

module.exports = Promise;

有哪理解不透彻的地方期待大佬指点