簡體   English   中英

Javascript:回調 function 與正常 function 通話

[英]Javascript: callback function vs normal function call

我是 JavaScript 的新手,我對回調與正常的 function 調用以及何時在真實場景中使用回調感到困惑。

有人可以告訴我,以下兩種實現方式有何不同? 或使回調比正常的 function 調用有用的真實案例場景?

使用正常的 function 呼叫

function getDetails(){
    setTimeout(() => {
        console.log("DETAILS")
    }, 2000);
}

function getUser(){
    setTimeout(() => {
        console.log("USER");
        getDetails(); // Normally calling the function
    }, 3000);
}

getUser();

使用回調

function getDetails(){
    setTimeout(() => {
        console.log("DETAILS")
    }, 2000);
}

function getUser(callback){
    setTimeout(() => {
        console.log("USER");
        callback(); // Calling the function
    }, 3000);
}

getUser(getDetails);

您展示的兩個示例在技術上沒有區別(假設您不會在調用getDetails之前修改它)。 有用的是調用回調的 function 不必知道要調用的確切 function(並且可以根據需要與不同的調用一起使用)。 例如,事件偵聽器或對Array.prototype.map的回調僅對回調模式有意義。

但是你展示的場景理想情況下也不會使用——它應該被重組為使用異步/等待:

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))

async function getDetails (user) {
  await sleep(2000)
  console.log('DETAILS', user)
  return 'some details'
}

async function getUser (userId) {
  await sleep(3000)
  console.log('USER', userId)
  return 'some user' 
}

async function main () {
  const user = await getUser(123)
  const details = await getDetails(user)
  console.log('got these details:', details)
}

main().catch(e => console.error('Failed to fetch data:', e))
// If you are in an environment that supports top-level await, 
// you can just use `await main()` instead

我添加了更多示例內容來說明真實用例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM