最近在刷面試題時,遇到了這么一道 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.