简体   繁体   中英

Why use callbacks when you can just call functions globally in Javascript?

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?

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.

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);
});

因为第一个示例使其可重用,所以如果要切换getResults的行为并改为调用其他函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM