promise.resolve 接收 thenable 时会执行 thenable-to-promise 转换,即调用其 then 方法并传入 resolve/reject,后续状态由该方法内对回调的调用决定;若 then 抛异常,则返回 rejected promise。

当 Promise.resolve 接收一个 thenable 对象(即带有 then 方法的对象)时,它会**尝试将其“吸收”为 Promise**,而不是直接包装成一个已解决的 Promise。这个过程本质上是执行一次“thenable-to-promise 转换”,其行为与 new Promise((resolve, reject) => resolve(thenable)) 一致。
什么是 thenable?
一个对象只要拥有可调用的 then 方法(形如 then(onFulfilled, onRejected)),就被视为 thenable。例如:
const myThenable = {
then(onFulfilled, onRejected) {
console.log('then called');
onFulfilled('from thenable');
}
};
Promise.resolve 如何处理 thenable?
它不会立即返回一个 fulfilled 状态的 Promise,而是:
- 检查传入值是否为对象或函数,且具有可调用的
then属性; - 若满足,则立即以该 thenable 为参数,调用 Promise 的 resolve 算法(即 [[Resolve]] 内部方法);
- 该算法会尝试调用
thenable.then,并将resolve和reject作为参数传入; - 后续状态由 thenable 内部的
onFulfilled/onRejected调用决定 —— 它可能同步或异步地调用其中一个回调。
关键行为示例
以下代码展示了实际效果:
const thenable = {
then(resolve, reject) {
console.log('1. then invoked');
setTimeout(() => {
console.log('2. resolving with "hello"');
resolve('hello');
}, 0);
}
};
const p = Promise.resolve(thenable);
console.log('3. Promise created');
p.then(val => console.log('4. final value:', val));
// 输出顺序:
// 1. then invoked
// 3. Promise created
// 2. resolving with "hello"
// 4. final value: hello
可见:Promise 创建是同步的,但内部等待 thenable 的 resolve 调用才真正 settled;整个链遵循 Promise 规范的异步调度逻辑(微任务队列)。
注意:不是所有 thenable 都安全
如果 thenable 的 then 方法抛出异常,Promise.resolve 返回的 Promise 会变为 rejected 状态:
const badThenable = {
then() {
throw new Error('boom');
}
};
Promise.resolve(badThenable)
.catch(err => console.log(err.message)); // 'boom'
此外,若 then 被多次调用、或同时调用 resolve 和 reject,Promise 规范要求只接受第一次调用,其余忽略。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











