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
相关产品推荐
相关产品推荐

