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);
getUser(getDetails)andgetUser(getSecondUser)orgetUser(writeResult). You don't have these options in the first version wheregetDetailsis hardcoded.