美文网首页
promise实现原理

promise实现原理

作者: 南方四季 | 来源:发表于2018-08-26 17:32 被阅读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);

        }

      });

    };

    相关文章

      网友评论

          本文标题:promise实现原理

          本文链接:https://www.haomeiwen.com/subject/wuioiftx.html