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

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What exactly is it that you're unclear about? Not having a parameter for the callback - which is effectively removing the "callback" - is like not having a return statement in your function.
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
That's like putting more code in a normal function, but still having it not return results to its caller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.