• 【笔记】实现一个简易的Promise


    const PENDING_STATE = "pending";
    const FULLFILL_STATE = "fullfilled";
    const REJECTED_STATE = "refected";
    
    class Promise {
      constructor(executor) {
        if (typeof executor !== "function") {
          throw new Error("Promise executor must be a function.");
        }
        this.__state = PENDING_STATE;
        this.__chains = [];
    
        const resolve = res => {
          // 当且仅当状态是 pending 状态时才可以调用resolve或者reject,防止二次调用。
          if (this.__state !== PENDING_STATE) return;
    
          // resolve要处理promise,判断是否有then属性
          if (res && typeof res.then === "function") {
            return res.then();
          }
    
          this.__state = FULLFILL_STATE;
          this.__internalValue = res;
    
          for (const { onFullFilled } of this.__chains) {
            onFullFilled(res);
          }
        };
    
        const reject = err => {
          if (this.__state !== PENDING_STATE) return;
          this.__state = REJECTED_STATE;
          this.__internalValue = err;
    
          for (const { onRejected } of this.__chains) {
            onRejected(err);
          }
        };
    
        // 规范中,Promise初始化就调用executor
        try {
          executor(resolve, reject);
        } catch (err) {
          // 如果处理器函数抛出一个同步错误,我们认为这是一个失败状态
          reject(err);
        }
      }
    
      then(onFullFilled, onRejected) {
        return new Promise((resolve, reject) => {
          // 参考上述的constructor实现
          const _onFullFilled = res => {
            try {
              resolve(onFullFilled(res));
            } catch (err) {
              reject(err);
            }
          };
    
          const _onRejected = err => {
            try {
              reject(onRejected(res));
            } catch (err) {
              reject(err);
            }
          };
    
          if (this.__state === FULLFILL_STATE) {
            _onFullFilled(this.__internalValue);
          } else if (this.__state === REJECTED_STATE) {
            _onRejected(this.__internalValue);
          } else {
            this.__chains.push({
              onFullFilled: _onFullFilled,
              onRejected: _onRejected
            });
          }
        });
      }
    }
  • 相关阅读:
    wcf常用的概念
    WebApi初探之路由配置
    NuGet Package Manager 实用命令
    WebApi初探之基本操作(CRUD)
    Excel操作类
    在Runbook中添加Checkpoint-workflow
    总结PowerShell的常用命令
    alt text 与 tooltip区别
    IFrame 获取内容
    WP8.1 实现Continuation程序(打开文件,保存文件等)
  • 原文地址:https://www.cnblogs.com/smileSmith/p/8920234.html
Copyright © 2020-2023  润新知