Reputation: 165
I'm sure there's a thread about this, but for the life of me I can't find it. I know this is a classic problem so sorry if this question is repetitive, but none of the articles/threads I have read address this seemingly obvious question that I have.
Consider this example
function serverRequest(query, callback){
setTimeout(function(){
var response = query + "full!";
callback(response);
},5000);
}
function getResults(results){
console.log("Response from the server: " + results);
}
serverRequest("The glass is half ", getResults);
This code snippet works exactly as it looks it should. However, as someone new to the concept of callbacks, why are we passing getResults
as an argument when we can just skip doing that and call it normally?
function serverRequest(query){
setTimeout(function(){
var response = query + "full!";
getResults(response);
},5000);
}
function getResults(results){
console.log("Response from the server: " + results);
}
serverRequest("The glass is half ");
According to my testing, this second snippet works perfectly well, no need for passing functions as callbacks. What exactly am I missing here?
Upvotes: 0
Views: 219
Reputation: 57723
Short answer? Functions in the global scope is fine until you have 10000 of them.
Typically you don't want to put anything in the global scope at all, to avoid naming conflicts and whatnot. So the global scope is usually not a consideration.
Callbacks aren't great though, all the cool kids use Promises.
function serverRequest(query) {
return new Promise(function (resolve) {
setTimeout(function(){
var response = query + "full!";
resolve(response);
},5000);
});
}
serverRequest("The glass is half ").then(function (results) {
console.log("Response from the server: " + results);
});
Upvotes: 2
Reputation: 332
Because the first example makes it reusable, if you want to switch out the behavior of getResults and call a different function instead.
Upvotes: 1
Reputation: 944425
For the same reason as you are passing a function to setTimeout
.
So you can reuse the logic of the serverRequest
without hard-coding what it does with the data it generates.
Upvotes: 3