I have been reading about asynchronous programming in javascript, and came across callback: Javascript Callback.
I will show two of the examples:
Example 1: Not using callback
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2) {
let sum = num1 + num2;
myDisplayer(sum);
}
myCalculator(5, 5);
Example 2: Using callback
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
My questions:
- What is meant by the comment:
The problem with the example (here Example 1), is that you cannot prevent the calculator function from displaying the result.
What is preventing the calculator function from displaying the result in Example 2? Since both of the examples is waiting for a calculation, meaning the current thread would not continue before the calculation is done, and the callback seems to be excess.
- Wouldn't these two examples do the same thing, meaning there's no need for callback in this case?
I see the use case of callback if thelet sum = num1 + num2would have been replaced with a call to query a external database.
myCalculator(5, 5, myLogger);that would log the result instead of displaying it. The point is to be given the choice, instead of hardcoding what happens when themyCalculatoris called.