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

