Promise.resolve 什么时候读取 then?用 getter 看清两段时序

作者:函数茶馆时间:2026-12-03浏览:110

用两个 getter 对比 Promise.resolve 读取 then、调用 then 和传播拒绝的时序。

接第三方库时,经常会用 Promise.resolve() 把普通值和 thenable 接进同一条 Promise 链。要是对方把 then 写成了 getter,这行封装代码就会先跑一段第三方逻辑。给读取和调用分别加一条日志,就能看出它们各自发生在什么时候。

先把读取 then 和调用 then 分开看

示例里,getter 一进来就打印 get then,随后返回一个函数。等函数真的被调用,才会看到 call then,这时它用 ready 兑现 Promise。前后的两条日志用来标清同步代码的边界。

{
  const source = {
    get then() {
      console.log('get then');
      return function (resolve) {
        console.log('call then');
        resolve('ready');
      };
    }
  };

  console.log('start');
  const result = Promise.resolve(source);
  result.then(value => console.log('value: ' + value));
  console.log('end');
}
依次打印 start、get then、end、call then 和 value: ready
预期控制台输出。读取 then 发生在 end 前,调用发生在 end 后。

在 Promise.resolve(source) 返回之前,就已经同步读过一次 source.then。取到函数以后,解析过程把这个函数保存下来,安排一个 Promise 作业,稍后以 source 为 this 调用。示例里的函数调用 resolve('ready') 时,先前注册的 result.then() 回调才入队。最后两行各来自一个作业。

同步读取 then,读取抛错时拒绝,否则图中沿可调用分支安排调用 then 和执行回调
可调用分支经过两次排队。读取时抛出的错误直接让 Promise 进入拒绝状态。

如果 getter 一读就抛错

把 getter 改成直接抛错,再在调用外面套一层 try...catch。只要能看到紧随其后的 resolve returned,就知道 Promise.resolve() 已经把返回值交出来了。

{
  const broken = {
    get then() {
      console.log('get broken.then');
      throw new Error('invalid then');
    }
  };

  try {
    const result = Promise.resolve(broken);
    console.log('resolve returned');
    result.catch(error => console.log('rejected: ' + error.message));
  } catch (error) {
    console.log('thrown: ' + error.message);
  }
}
依次打印 get broken.then、resolve returned 和 rejected: invalid then
预期控制台输出。同步代码拿到了返回值,随后由 catch 回调报告错误。

调用返回时,Promise 已经拒绝,拒因就是 getter 抛出的错误。随后挂上的 result.catch() 会异步执行。这次调用正常返回,所以外层 catch 不会打印 thrown。如果 getter 正常返回了数字之类的不可调用值,Promise 会用传给 Promise.resolve() 的原对象兑现。

排查 SDK 返回的 thenable 时,可以先在 Promise.resolve() 前后各留一条日志,再给返回的 Promise 接好拒绝处理。这样就能顺着日志定位问题是在读取属性时发生,还是到了后面的调用阶段。写测试时,直接对返回的 Promise 断言拒因,外层的 try...catch 只覆盖同步抛错。

作者最新文章
相关文章
更多