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

Promise链中箭头函数与console.log传入方式的行为差异解惑

关于Promise链中then块行为的两个问题解答

Q1:为何在Promise链的then块中直接传入console.log会输出undefined?

代码示例:

new Promise((resolve, reject) => {
  console.log(4)
  resolve(5)
  console.log(6)
}).then(() => console.log(7))
.catch(() => console.log(8))
.then(() => console.log(9))
.catch(() => console.log(10))
.then(() => console.log(11))
.then(console.log)
.finally(() => console.log(12))

输出:

4
6
7
9
11
undefined
12

解释:

当你在then里直接传console.log时,这个函数会被Promise自动调用,参数是上一个then执行后的返回值。

看链的倒数第二个then:then(() => console.log(11)),这个箭头函数只执行了console.log(11),没有显式返回任何值,所以它的返回值默认是undefined。

接下来的then(console.log)就会把这个undefined当作参数传给console.log,执行console.log(undefined),自然就输出了undefined。


Q2:为何在then块中通过箭头函数返回console.log时,该then块无对应输出?

代码示例:

new Promise((resolve, reject) => {
  console.log(4)
  resolve(5)
  console.log(6)
}).then(() => console.log(7))
.catch(() => console.log(8))
.then(() => console.log(9))
.catch(() => console.log(10))
.then(() => console.log(11))
.then(()=>console.log)
.finally(() => console.log(12))

输出:

4
6
7
9
11
12

解释:

这里的箭头函数()=>console.log只是返回了console.log这个函数本身,并没有执行它。Promise的then方法会接收这个返回的函数,但不会主动去调用它——只有当你返回的是Promise时才会等待其状态变更,普通函数只会被当作下一个then的参数传递,而这里后面没有更多的then环节,所以这个console.log函数根本没被执行,自然不会有输出。


内容的提问来源于stack exchange,提问作者SHOBHIT GARG

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 04:37:02