0

I'm lerning how callback works, and i'm trying this simple code.

function sayHi(name) {
    return `Hi ${name}`;
}
    
    
    
function fetchData(callBack) {
    
    setTimeout(() => {
        let name = "Vincenzo";
        callBack(name);
    }, 2000)
}
    
console.log(fetchData(sayHi));

Why the return inside the sayHi function does not produce any output? instead if i write the code inside a console.log(); it works....

Can anyone explain me this? and how to get the output with the return?

Thanks!

  • Where does it *return to*? To here `callBack(name)`. And you're not doing anything with it there. `console.log(fetchData(..))` doesn't log anything because `fetchData` doesn't `return` anything. – deceze Aug 05 '20 at 08:50
  • console.log() - work on the synchronous mode. Your fetchData is working asynchronous. It is generating output after 2s but by then console.log is completed. It is getting no value so it is displaying undefined. Still you are returning value from that function but due to async behaviour it is not displaying any output. you cannot get the output with this return either you need to use console in the function or remove async behvaiour. – deepak Aug 05 '20 at 09:02
  • Javascript works synchronously. Whatever async functionality it is handled by browser api. setTimeout is provided by browser Api. It will execute once all the synchronous code execution is done. Call back having async behvavior it is going to produce result once all the synchronous code is done. – deepak Aug 05 '20 at 09:06
  • Javascript uses stacks to execute the synchronous code. All async code it is handled by browser api. Javascript execute code line by line. If there is any async code then it is going to be handled by browser. Browser will wait till the stack is empty. With event loop it will send it to stack and give the output. Same thing happening here. – deepak Aug 05 '20 at 09:11

0 Answers0