You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Promise处理器间控制流:两段代码输出差异原因解析

两段Promise代码输出差异解析

控制流拆解

Code 1 执行流程

  • 创建motherPromise时,立即执行内部执行器函数,调用reject()将Promise状态置为rejected,并存储错误对象。
  • 为motherPromise绑定catch回调:当Promise处于rejected状态时触发该回调,打印Hello。此时原Promise的拒绝状态被完全处理,无未捕获错误。

Code 2 执行流程

  • 同样创建motherPromise,状态变为rejected并存储错误。
  • 调用motherPromise.then(...):仅传入成功态回调,未指定失败处理逻辑。由于原Promise是rejected状态,这个then会返回一个新的rejected状态Promise(继承原错误信息)。
  • 调用motherPromise.catch(...):该回调处理了原motherPromise的拒绝状态,打印Hello。
  • 关键问题:步骤2中then返回的新Promise的拒绝状态没有被任何catch处理,JavaScript引擎会将这个未捕获的Promise拒绝抛出到控制台,也就是你看到的额外错误日志。

核心差异原因

Promise的then和catch方法都会返回全新的Promise实例,而非修改原Promise状态:

  • Code 1中,原Promise的拒绝状态被自身绑定的catch处理,没有遗留未处理的拒绝。
  • Code 2中,单独调用的motherPromise.then(...)生成了一个未被处理的rejected Promise,这是控制台多出错误信息的根本原因。

如果要消除Code 2的额外错误,需改用链式调用让then返回的Promise被后续catch处理:

const motherPromise = new Promise((resolve, reject) => {
  reject(new Error("Milk has spilled due to overboiling"));
});

motherPromise
  .then((resolveValue) => console.log(`${resolveValue} and Stove was shut`))
  .catch((rejectValue) => console.log("Hello"));

内容的提问来源于stack exchange,提问作者Intangible _pg18

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 01:07:47