最近看到了一个有趣的Promise的方法,这里记录下来

 <script>
    class MyPromise {    
      constructor(executor) {
        // 初始化state赋值为pending
        this.state = "pending";
        // 定义成功的 值
        this.value = undefined;
        //定义失败的 原因
        this.reason = undefined;
        //定义成功存起来的数组
        this.onResolvedCallbacks = [];
        //定义失败存起来的数组
        this.onRejectedCallbacks = [];
        let resolve = (value) => {
          // state改变,resolve调用就会失败
          if (this.state === "pending") {
            this.value = value;
            //resolve调用后,state转为fulfilled
            this.state = "fulfilled";
            // 一旦resolve执行,调用成功数组的函数
            this.onResolvedCallbacks.forEach(function (fn) {
              return fn(value);
            });
            //也可以使用es6语法 简写
            //this.onResolvedCallbacks.forEach(fn => fn(value));
          }
        };
        let reject = (reason) => {
          // state改变,reject调用就会失败
          if (this.state === "pending") {
            this.reason = reason;
            // reject调用后,state转为失败状态
            this.state = "rejected";
            // 一旦reject执行,调用失败数组的函数
            this.onRejectedCallbacks.forEach(fn => fn(reason)); //简写
          }
        };

        // new MyPromise后的实例具有状态, 默认状态是等待,当执行器调用resolve后, 实例状态为成功状态;当执行器调用reject后,实例状态为失败状态
        try {
          executor(resolve, reject);
        } catch (error) {
          reject(error);
        }
      }

      // then中有两个参数 ,把第一个参数叫做then的成功回调,把第二个参数叫做then的失败回调,这两个参数也都是函数,当执行器调用resolve后,then中第一个参数函数会执行,当执行器调用reject后,then中第二个参数函数会执行
      then(onFulfilled, onRejected) {
        // 状态为fulfilled,执行onFulfilled,传入成功的值
        if (this.state === "fulfilled") {
          onFulfilled(this.value);
        }
        // 状态为rejected,执行onRejected,传入失败的原因
        if (this.state === "rejected") {
          onRejected(this.reason);
        }
        // 状态为pending时 
        if (this.state === "pending") {
          // onFulfilled传入到成功数组
          this.onResolvedCallbacks.push(onFulfilled);
          // onRejected传入到失败数组
          this.onRejectedCallbacks.push(onRejected);
        }
      }
    }
	//当new MyPromise实例 会立即调用constructor(executor)
    let p = new MyPromise((resolve, reject) => {
      console.log("开始");
      setTimeout(function () {
        resolve("我成功了");
      }, 2000);
    });
    
    p.then(
      (resolve) => {
        console.log("success:" + resolve);
      },
      (reject) => {
        console.log("error:" + reject);
      }
    );
    console.log("结束");
  </script>

转载于:https://blog.csdn.net/l_XIANA/article/details/110141804?utm_medium=distribute.pc_category.none-task-blog-hot-9.nonecase&depth_1-utm_source=distribute.pc_category.none-task-blog-hot-9.nonecase

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/smileZAZ/p/14049396.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程