Sorry if there's already other question around this subject. I couldn't find one.
Could somebody elaborate on how this code works?
I wasn't expecting the result from foo() to be available inside the callback declaration that is being passed as a parameter of foo.
What is the order of events that happens in a situation like this?
It's like the function returns first and only then it creates its own parameter? How does that make sense?
const foo = (callback) => {
setTimeout(callback,500);
return 42;
};
const result = foo(() => {
console.log('From callback...');
console.log('result:',result);
})
Similar to this:
const id = setTimeout(() => console.log('id',id),500);
Firstly foo runs, which sets the callback to be run after 500ms, and then returns with 42. That gets stored in the result variable.
After 500ms the callback from foo's parameter gets called, and finds the variable result as a global variable and prints it out (which is set to be 42)