美文网首页
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);

    }

  });

};

相关文章

  • javascript的promise

    实现原理 Promise.all() Promise.race()

  • 转载Promise实现原理,自己记忆备用

    Promise实现原理(原文)

  • Promise

    什么是Promise Promise解决了什么问题 Promise/A+规范 Promise的原理(如何实现链式调...

  • promise原理

    title: Promise实现原理date: 2018-02-26 17:25:09tags: promise ...

  • 手写Promise

    参考:Promise实现原理(附源码) promise的注意点: Promise特点 1.状态不可变 2.值穿透,...

  • 八(1)、Promise(周) ------ 2020-02-2

    1、什么是Promise: 2、通过原生JS实现简单的Promise原理,理解Promise如何管控异步编程: 3...

  • 实现 Promise

    实现 Promise 此代码基本源于大佬在掘金上发的文章Promise实现原理(附源码), 此文写得相当详细, 非...

  • 宏观看Promise

    自定义Promise实现,来了解他的运行原理

  • promise实现原理

    伪代码 class my_promise { constructor(fun) { const that =...

  • Promise实现原理

    当我们用$.ajax()这个API的时候,是想使用Ajax去请求数据。并且在回调函数success里面去操作我们得...

网友评论

      本文标题:promise实现原理

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