try catch的执行顺序

无意中看到一段大神的代码,大体结构如下

function handleThenable(promise, value) {
      var resolved;

      try {
        if (promise === value)
          { throw new TypeError('A promises callback cannot return that same promise.'); }

        if (value && (typeof value === 'function' || typeof value === 'object'))
        {
          var then = value.then;  // then should be retrived only once

          if (typeof then === 'function')
          {
            then.call(value, function(val){
              if (!resolved)
              {
                resolved = true;

                if (value !== val)
                  { resolve(promise, val); }
                else
                  { fulfill(promise, val); }
              }
            }, function(reason){
              if (!resolved)
              {
                resolved = true;

                reject(promise, reason);
              }
            });

            return true;
          }
        }
      } catch (e) {
        if (!resolved)
          { reject(promise, e); }

        return true;
      }

      return false;
    }

我的问题 这个函数handleThenable什么时候会 return false;

阅读 2.2k
2 个回答

20200627172933.png
格式化下就清晰了,不满足圈中的2个if条件返回false

if (promise === value)

会丢异常,走cache分支,返回true

if (value && (typeof value === 'function' || typeof value === 'object')) {
    var then = value.then;  // then should be retrived only once
    if (typeof then === 'function')
    ...

虽然上面的 if 判断了 object 但后面并没有进一步处理,所以只有 value 是 function 才会走里面的分支,返回 true。

除了这两种情况都会返回false

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题