I was reading about callback functions here (also in an online course which I am participating) and now I am stuck. The reason is that I cannot understand Why do I need to use callback functions if I can simply call them. Exemples below:
1 - Using callback functions:
function showArticle(id, callbackSuccess, callbackError){
if (true){
callbackSuccess("This is a callback function", "It is very utilized.");
} else {
callbackError("Error on data recovery.");
}
}
var callbackSuccess = function(title, description){
document.write("<h1>" + title + "</h1>");
document.write("<hr>");
document.write("<p>" + description + "</p>");
}
var callbackError = function(error){
document.write("<p><b>Erro:</b>" + error + "</p>");
}
showArticle(1, callbackSuccess, callbackError);
2 - Here is my code not using callback functions and having the same results:
function showArticle(id){
if (true){
callbackSuccess("This is a callback function", "It is very utilized.");
} else {
callbackError("Error on data recovery.");
}
}
var callbackSuccess = function(title, description){
document.write("<h1>" + title + "</h1>");
document.write("<hr>");
document.write("<p>" + description + "</p>");
}
var callbackError = function(error){
document.write("<p><b>Erro:</b>" + error + "</p>");
}
showArticle(1);
Why should I use callback functions and not simply calling them in the example 2?