0

Maybe someone mark my question as duplicate or else but i am confusing about callback in JavaScript. I read from here a following piece of code

getText = function(url, callback) // How can I use this callback?
{
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
    if (request.readyState == 4 && request.status == 200)
    {
        callback(request.responseText); // Another callback here
    }
}; 
request.open('GET', url);
request.send();
}
function mycallback(data) {
    alert(data);
}
getText('somephpfile.php', mycallback); //passing mycallback as a method

and now if i change the above code and remove callbacks like following

getText = function(url) //Also remove from here  How can I use this callback?
{
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
    if (request.readyState == 4 && request.status == 200)
    {
        mycallback(request.responseText); //Now here i simply call that function
    }
}; 
request.open('GET', url);
request.send();
}
function mycallback(data) {
    alert(data);
}
getText('somephpfile.php'); //Remove (passing mycallback as a method)

So now what is difference now? If no difference then why use callbacks

Community
  • 1
  • 1
Blu
  • 4,036
  • 6
  • 38
  • 65
  • 1
    possible duplicate of [Why use callback in JavaScript, what are its advantages?](http://stackoverflow.com/questions/7070495/why-use-callback-in-javascript-what-are-its-advantages) – ashbuilds Mar 04 '14 at 13:56

1 Answers1

1

So now what is difference now? If no difference then why use callbacks

Your first function is more general (reusable). You can do all of these:

getText('somephpfile.php', console.log); // or
getText('somephpfile.php', alert); // or
getText('somephpfile.php', mycallback); // or
getText('somephpfile.php', yourcallback); // or
getText('somephpfile.php', whatever);

which will behave differently. In your second function, the getText cannot be used for anything else but alerting ajax data.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • What exactly is it that you're unclear about? Not having a parameter for the [callback](https://en.wikipedia.org/wiki/Callback_(computer_programming)) - which is effectively removing the "callback" - is like not having a `return` statement in your function. – Bergi Mar 04 '14 at 19:16
  • I send a `function` as a `parameter` to call later as a `callback` what if I call actual `function` where I call `callback` and not pass as a `parameter` in a `function` – Blu Mar 04 '14 at 19:41
  • That's like putting more code in a normal function, but still having it not `return` results to its caller. – Bergi Mar 04 '14 at 20:15