promise实现原理

2018-08-26  本文已影响0人  南方四季

伪代码

class my_promise {

  constructor(fun) {

    const that = this;

    this._queue = []; // 队列

    that._success_res = null;

    that._error_res = null;

    that.status = "";// 状态机

    fun(

      (...args) => {

        that._success_res = args;

        that.status = "success";

        that._queue.forEach(json => {

          json.fun1(...args);

        });

      },

      (...args) => {

        that._error_res = args;

        that.status = "error";

        that._queue.forEach(json => {

          json.fun2(...args);

        });

      }

    );

  }

  then(fun1, fun2) {

    if (this.status === "success") {

      fun1(this._success_res);

    } else if (this.status === "error") {

      fun2(this._error_res);

    } else {

      // 异步操作还没完

      this._queue.push({ fun1, fun2 });

    }

  }

}

my_promise.all = arr => {

  let list = [];

  return new my_promise((resolve, reject) => {

    let i = 0;

    next();

    function next() {

      arr[i].then(res => {

        list.push(res);

        i++;

        if (i === arr.length) {

          resolve(list);

        } else {

          next();

        }

      }, reject);

    }

  });

};

上一篇下一篇

猜你喜欢

热点阅读