关于Promise的个人理解

125 阅读1分钟

什么是Promise

Promise是异步编程的一种解决方案,比传统的解决方案(回调函数)更合理、更强大,简单的来说Promise就是一个容器,里面保存着未来才会结束的事件的结果(通常是一个异步操作)。

Promise的特点

  1. Promise对象的状态不受外界影响,共有三种状态:pending(进行中)、fulfilled(已成功)、rejected(已失败)。只有异步操作的结果可以决定当前是哪一种状态,其他任何操作都无法改变这个状态。
  2. Promise对象的状态一旦改变,无法再次改变,且状态只有从pending变为fulfilled和从pending变为rejected两种结果。
  3. Promise构造函数必须接收一个函数作为参数,该函数包含resolve和reject。

自定义Promise

class MyPromise {
    constructor(fn) {
        this.status = 'PENDING';
        this.doneList = [];
        this.failList = [];
        fn(this.resolve.bind(this), this.reject.bind(this));
    }
    
    done(handle) {
        if (typeof handle === 'function') {
            this.doneList.push(handle);
        } else {
            throw new Error('缺少回调函数');
        }
    }
    
    fail(handle) {
        if (typeof handle === 'function') {
            this.failList.push(handle);
        } else {
            throw new Error('缺少回调函数');
        }
    }
    
    then(success, fail) {
        this.done(success || function () {});
        this.fail(fail || function () {})
    }
    
    resolve(data) {
        if (this.status !== 'PENDING') {
            return;
        }
        this.status = 'RESOLVED';
        this.doneList.forEach((item, key, arr) => {
            item(data);
            arr.shift();
        })
    }
    
    reject (data) {
        if (this.status !== 'PENDING') {
            return;
        }
        this.status = 'REJECTED';
        this.failList.forEach((item, key, arr) => {
            item(data);
            arr.shift();
        })
    }
}

// 应用
new MyPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('hello world');
    }, 2000)
}).then(res => {
    console.log(res);
});