關於.then(console.log)的理解


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

參考:https://stackoverflow.com/questions/50836242/how-does-thenconsole-log-and-then-console-log-in-a-promise-chain


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM