为何Promise实例化时执行构造函数代码,调用.then()却不重复执行?
Promise构造函数执行逻辑疑问
代码示例
const promise = new Promise((resolve, reject) => { console.log("working 1.0") setTimeout(() => { console.log("working 2.0") resolve([90, 70, 55]); }, 7000); }); console.log("Hi") promise.then(values => { console.log(values[1]); });
实际输出
working 1.0 Hi working 2.0 70
预期输出
working 1.0 Hi working 1.0 working 2.0 70
我的疑问:原本认为调用.then()时,new Promise()中初始化的整个函数会被再次调用,为什么实际不是这样?
核心原因:Promise构造函数的执行时机是实例化时,而非调用.then()时
- 当执行
new Promise(executor)时,传入的executor函数(即(resolve, reject) => {...})会立即同步执行,和后续是否调用.then()/.catch()完全无关,这就是第一次打印working 1.0的原因。 .then()的作用只是给已存在的Promise实例注册状态变更后的回调:当Promise从pending变为resolved时,触发你传入的回调函数,它不会重新触发executor的执行。
你的代码执行流程拆解
- 执行
new Promise(...),立即调用executor函数,打印working 1.0,同时启动7秒定时器。 - 同步执行
console.log("Hi"),打印Hi。 - 调用
promise.then(...),为该Promise注册回调,但此时Promise处于pending状态,回调暂不执行。 - 7秒后定时器触发,打印
working 2.0,调用resolve([90,70,55])将Promise状态改为resolved。 - Promise状态变更后,触发之前注册的
.then()回调,打印values[1]即70。
如果想要每次调用.then()都重新执行异步逻辑,需要把Promise的创建包装成函数:
function createPromise() { return new Promise((resolve, reject) => { console.log("working 1.0") setTimeout(() => { console.log("working 2.0") resolve([90, 70, 55]); }, 7000); }); } console.log("Hi") createPromise().then(values => { console.log(values[1]); }); // 再次调用会重新执行executor // createPromise().then(...);
每次调用createPromise()都会生成新的Promise实例,executor函数也会重新执行,就能得到你预期的多次working 1.0输出。
内容的提问来源于stack exchange,提问作者NeedHelpWithCode
相关产品推荐
相关产品推荐

