Promise.resolve 什么时候读取 then?用 getter 看清两段时序
用两个 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');
}

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

如果 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);
}
}

调用返回时,Promise 已经拒绝,拒因就是 getter 抛出的错误。随后挂上的 result.catch() 会异步执行。这次调用正常返回,所以外层 catch 不会打印 thrown。如果 getter 正常返回了数字之类的不可调用值,Promise 会用传给 Promise.resolve() 的原对象兑现。
排查 SDK 返回的 thenable 时,可以先在 Promise.resolve() 前后各留一条日志,再给返回的 Promise 接好拒绝处理。这样就能顺着日志定位问题是在读取属性时发生,还是到了后面的调用阶段。写测试时,直接对返回的 Promise 断言拒因,外层的 try...catch 只覆盖同步抛错。
JS 用递归输出从 1 到 n 再到 1 的数字:怎样让峰值只出现一次
2026-12-04
JS中slice、substring和substr三个字符串截取方法的区别
2026-12-04
JavaScript函数内使用return终止for循环的执行机制
2026-12-03
JS怎么通过解构赋值快速获取数组元素
2026-12-03
为什么JS map遍历后数组没变?常见误区解析
2026-12-03



