最近在刷面试题时,遇到了这么一道 Promise 真题:(考察值穿透)
Promise.resolve(1)
.then(Promise.resolve(2))
.then(3)
.then()
.then(console.log)
首先 Promise.resolve(1) 表示异步已经成功,接下来到 then 方法来执行对应的回调函数。
因为 then 方法里的参数只能是函数,所以一开始的三个 then 方法不会执行,知道遇到 console.log ,它是一个函数。
到了这里,我产生了疑惑,我没有给 log 方法传递参数,它是怎么打印出结果 1 的呢?
原来,Promise库本身会给它带参调用。下面是 stackoverflow 中搜到的答案:
This executes the console.log only after the promise has successfully resolved (requires one function call) and implicitly pass the result of the promise to to the console.log function.