• Promise


    首先声明定义类并声明Promise状态与值,有以下几个细节需要注意。

    • executor为执行者
    • 当执行者出现异常时触发拒绝状态
    • 使用静态属性保存状态值
    • 状态只能改变一次,所以在resolve与reject添加条件判断
    • 因为 resolverejected方法在executor中调用,作用域也是executor作用域,这会造成this指向window,现在我们使用的是class定义,this为undefined。
    class HD {
      static PENDING = "pending";
      static FULFILLED = "fulfilled";
      static REJECTED = "rejected";
      constructor(executor) {
        this.status = HD.PENDING;
        this.value = null;
        try {
          executor(this.resolve.bind(this), this.reject.bind(this));
        } catch (error) {
          this.reject(error);
        }
      }
      resolve(value) {
        if (this.status == HD.PENDING) {
          this.status = HD.FULFILLED;
          this.value = value;
        }
      }
      reject(value) {
        if (this.status == HD.PENDING) {
          this.status = HD.REJECTED;
          this.value = value;
        }
      }
    }

    下面测试一下状态改变

    <script src="HD.js"></script>
    <script>
      let p = new HD((resolve, reject) => {
        resolve("123");
      });
      console.log(p);
    </script>

     

  • 相关阅读:
    CF_402C Searching for Graph 乱搞题
    zoj Simple Equation 数论
    zoj 3757 Alice and Bob and Cue Sports 模拟
    uva_12535
    boj1267 Infinite’s Cave 树形dp + 背包
    CF_216_Div_2
    nxlog4go 简介
    log4go的一些改进设想
    nxlog4go 的配置驱动
    nxlog4go Log Levels and Pattern Layout
  • 原文地址:https://www.cnblogs.com/yyy1234/p/15829617.html
Copyright © 2020-2023  润新知