Promise 自己理解

58 阅读1分钟
  1. 为什么要用promise,解决什么问题? 场景一:多层级联,回显; 复杂化的场景会产生回调地狱(无限层的嵌套)

  2. Promise是什么? Promise => 承诺,诺言。 a.异步 b. 等待 => 成功resolve 失败reject (基于状态驱动,状态不可逆)

  3. Promise执行顺序

// 5 4 1 2 2 构造函数立即执行(同步执行),构造函数只执行一次,then(异步执行)可以执行多次。
    const promise = new Promise((resolve, reject) => {
        console.log(5);
        setTimeout(() => {
            console.log(1);
            resolve(2);
        }, 1000)
    })
    promise.then(res => {
        console.log(res);
    })
    promise.then(res => {
        console.log(res);
    })
    console.log(4);


  1. 手写Promise
// 1. 基础架构
    function myPromise(excutor){
        let self = this;
        self.value = null; // 成功结果
        self.reason = null; // 失败原因
        self.status = 'pedding'; // 状态
        self.onFulfilledCallbacks = [];
        self.onRejectedCallbacks = [];
        // 成功回调
        function resolve(value){
            // 4. 状态处理 等待 => 成功, 失败(状态不可逆)
            if(self.status === 'pedding'){
                self.value = value;
                self.status = 'fulfilled';
                // 7 状态改变依次取出 发布
                self.onFulfilledCallbacks.forEach(item => item(value));
            }
        }
        // 失败的回调
        function reject (reason) {
            if(self.status === 'pedding'){
                self.reason = reason;
                self.status = 'rejected';
                self.onRejectedCallbacks.forEach(item => item(reason));
            }
        }
        // 3.立即执行一遍
        try {
            excutor(resolve, reject);
        } catch (error) {
            reject(error)
        }
    }
    // 2. then 方法
    myPromise.prototype.then = function(onFulfilled, onRejected){
        // 改变状态走then
        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : function (data) { resolve(data)};
        onRejected = typeof onRejected === 'function' ? onRejected : function (err) { throw err};
        // 发布订阅者模式 6 订阅
        if(this.status === 'pedding'){
            this.onFulfilledCallbacks.push(onFulfilled);
            this.onRejectedCallbacks.push(onRejected);
        }
    }
    let demo = new myPromise((resolve, reject) => {
        console.log('11111111111');
        setTimeout( () => {
            resolve(123);
        }, 2000)
    })
    demo.then( data => console.log(data));