text: import { isFunction, isObject } from '@hai2007/tool/type';
  
  export var changeState = function (data, state) {
  
      // 更改状态
      this.__state = state;
      this.__value = data;
  
      // 由于状态改变了，触发对then，finnaly，catch等的执行更新
      this.$$triggerEvent();
  
  };
  
  export var triggerEvent = function () {
  
      // 这个方法的任务就是把__hocks中记录的方法依次执行了
      // 什么时候会停止？两种情况：
      // 1.队列执行完了
      // 2.遇到其中一个执行方法返回Promise
  
      var currentHock = null;
  
      // 同意状态就去寻找下一个onFulfilled
      // 拒绝状态就去寻找下一个onRejected
      // 数组下标0和1分别记录这两个状态，因此先根据状态确定下标即可
      var index = this.__state == 'fulfilled' ? 0 : 1, i;
  
      // 可能找到，可能到结尾都没有找到
      while (this.__hocks.length > 0) {
  
          if (isFunction(this.__hocks[0][index])) {
              currentHock = this.__hocks.shift();
              break;
          }
  
          // 对于路过的finally执行一下
          else if (isFunction(this.__hocks[0][2])) {
              this.__hocks[0][2]();
          }
  
          this.__hocks.shift();
  
      }
  
      // 如果找到了
      if (currentHock !== null) {
          var result = currentHock[index](this.__value);
  
          // 如果是Promise
          if (isObject(result) && result.constructor === this.constructor) {
              for (var i = 0; i < this.__hocks.length; i++) {
                  result.__hocks.push(this.__hocks[i]);
                  if (result.__state != 'pending') result.$$triggerEvent();
              }
  
              this.then = function (onFulfilled, onRejected) {
  
                  result.then(onFulfilled, onRejected);
              };
              this.catch = function (onRejected) {
  
                  result.catch(onRejected);
              };
              this.finally = function (callback) {
  
                  result.finally(callback);
              };
  
          }
  
          // 否则
          else {
  
              this.__value = result;
              this.__state = "fulfilled";
              this.$$triggerEvent();
  
          }
  
      }
  
  };
  
  export var doResolve = function (doback, that) {
  
      // 防止重复修改状态
      var done = false;
  
      try {
          doback(function (value) {
              if (done) return; done = true;
              that.$$changeState(value, 'fulfilled');
  
          }, function (reason) {
              if (done) return; done = true;
              that.$$changeState(reason, 'rejected');
  
          });
      } catch (error) {
          if (done) return; done = true;
          that.$$changeState(error, 'rejected');
      }
  
  };
  