0

original thread http://recurial.com/programming/understanding-callback-functions-in-javascript/

example js code,

function some_function2(url, callback) {
    var httpRequest; // create our XMLHttpRequest object
    if (window.XMLHttpRequest) {
        httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        // Internet Explorer is stupid
        httpRequest = new
            ActiveXObject("Microsoft.XMLHTTP");
    }

    httpRequest.onreadystatechange = function() {
        // inline function to check the status
        // of our request
        // this is called on every state change
        if (httpRequest.readyState === 4 &&
                httpRequest.status === 200) {
            callback.call(httpRequest.responseXML);
            // call the callback function
        }
    };
    httpRequest.open('GET', url);
    httpRequest.send();
}
// call the function
some_function2("text.xml", function() {
    console.log(this);
});
console.log("this will run before the above callback");

the explanation in this thread,

In this example we create the httpRequest object and load an XML file. The typical paradigm of returning a value at the bottom of the function no longer works here. Our request is handled asynchronously, meaning that we start the request and tell it to call our function when it finishes.

We’re using two anonymous functions here. It’s important to remember that we could just as easily be using named functions, but for sake of brevity they’re just written inline. The first anonymous function is run every time there’s a state change in our httpRequest object. We ignore it until the state is 4 (meaning it’s done) and the status is 200 (meaning it was successful). In the real world you’d want to check if the request failed, but we’re assuming the file exists and can be loaded by the browser. This anonymous function is assigned to httpRequest.onreadystatechange, so it is not run right away but rather called every time there’s a state change in our request.

When we finally finish our AJAX request, we not only run the callback function but we use the call() function. This is a different way of calling a callback function. The method we used before of just running the function would work fine here, but I thought it would be worth demonstrating the use of the call() function. Alternatively you could use the apply() function (the difference between the two is beyond the scope of this tutorial, but it involves how you pass arguments to the function).

The neat thing about using call() is that we set the context in which the function is executed. This means that when we use the this keyword inside our callback function it refers to whatever we passed as the first argument for call(). In this case, when we refer to this inside our anonymous callback function we are referring to the responseXML from the AJAX request.

Finally, the second console.log statement will run before the first, because the callback isn’t executed until the request is over, and until that happens the rest of the code goes right on ahead and keeps running.

Finally, these are the questions i have.

The first anonymous function is run every time there’s a state change in our httpRequest object.

okay, i checked with debug mode that this anonymous function is calling everytime until readyState == 4. But who is calling this every time function???

2) Cannot understand the difference usage between call(), callback.call() , callback.apply()

my question is, if i change the code like

  callback(httpRequest.responseXML);

// call the function
some_function2("text.xml", function(response) {
    console.log(response);
});

isn't this same as the original code?

async and callback is really HARD:(

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Canna
  • 3,614
  • 5
  • 28
  • 33
  • "*who is calling this function*" - the `XMLHttpRequest` object is. It's an in-build object in your browser working on low-level programming. – h2ooooooo Feb 05 '14 at 15:12

3 Answers3

0

But who is calling this every time function?

The XMLHttpRequest object.

It's the same principle as:

button.addEventListener('click', foo);

The function foo is called every time the button is clicked.

Cannot understand the difference usage between call(), callback.call(), callback.apply()

The latter two allow you to pass in the context (the value of this inside the function) as an argument.

if i change the code like … isn't this same as the original code

Yes.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

The problem with the usage of .call() here is that it should not work that way.

The first parameter of .call() and .apply() is supposed to be non-optional and defines the value of this inside the called function.

The difference between .call() and .apply() is that .call() expects the parameters to the function as comma separated, whereas .apply() expects the parameters to be inside an array.

devnull69
  • 16,402
  • 8
  • 50
  • 61
0

But who is calling this every time function???

Mighty forces deep within your computer :-) First, you will need to understand how the asynchronous event loop works: JavaScript is executed whenever something happens, and then it waits for the next thing to happen. So in this case, the HTTP manager code notifies the JavaScript interpreter that it has a new readyState, and triggers a readyStateChange event. When the JS event queue scheduler has found time for it, it invokes your event listener.

difference usage between call(), callback.call(), callback.apply()

First, you need to understand how the this keyword works. When just using callback(), the context of the function is not set. You can use the call method of the function to specify it, like the article you read says. Also check out What is the difference between call and apply?.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375