简体   繁体   English

Javascript:回调 function 与正常 function 通话

[英]Javascript: callback function vs normal function call

I am new to JavaScript and I am so confused with callbacks vs normal function calls and when to use callbacks in a real scenario.我是 JavaScript 的新手,我对回调与正常的 function 调用以及何时在真实场景中使用回调感到困惑。

Can someone please tell me, how both the below implementations are different from each other?有人可以告诉我,以下两种实现方式有何不同? or a real case scenario that makes a callback useful than a normal function call?或使回调比正常的 function 调用有用的真实案例场景?

Using the normal function call使用正常的 function 呼叫

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

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

getUser();

Using Callback使用回调

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

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

getUser(getDetails);

There is no difference technically in the two examples you showed (assuming you won't modify getDetails before it is called).您展示的两个示例在技术上没有区别(假设您不会在调用getDetails之前修改它)。 What makes it useful is that the function that calls the callback doesn't have to know the exact function to call (and could be used with different ones as needed).有用的是调用回调的 function 不必知道要调用的确切 function(并且可以根据需要与不同的调用一起使用)。 For instance, something like an event listener or the callback to Array.prototype.map only makes sense with the callback pattern.例如,事件侦听器或对Array.prototype.map的回调仅对回调模式有意义。

But the scenario you showed ideally wouldn't use either - it should be restructured to use async/await:但是你展示的场景理想情况下也不会使用——它应该被重组为使用异步/等待:

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

I added some more example stuff to illustrate a real use case.我添加了更多示例内容来说明真实用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM