Home > Software engineering >  Javascript: callback function vs normal function call
Javascript: callback function vs normal function call

Time:10-04

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.

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?

Using the normal function call

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);

CodePudding user response:

There is no difference technically in the two examples you showed (assuming you won't modify getDetails before it is called). 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). For instance, something like an event listener or the callback to Array.prototype.map only makes sense with the callback pattern.

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.

  • Related