Question

I'm having trouble figuring out what is ultimately returned in the callback portion of this ajax request...

Here's the code:

        function (fn) {
        $.ajax({
          url: "https://api.parse.com/1/classes/chats",
          data: {
             order: 'createdAt',
             limit: 10
          },
          type: "GET"
        })
        .done(function(data) {
          var messages = [];
          for (var i = 0, len = data.results.length; i < len; i++) {
            messages.push(data.results[i].text);
          }

          return fn(messages);
        });
      },

I understand the top half is performing a GET request to the server. This top portion then returns a JSON object that contains a JSON array that lists the objects.

Then the callback is executed upon successful retrieval of data from the server. The callback function processes a response by adding each server-retrieved message to a messages array.

But then what is confusing me is what is ultimately returned by the callback...

return fn(messages);

"fn" is also the argument to the initial function call. Can someone please explain what, exactly, is going on here? And what is ultimately being returned by the callback? And is what's returned by that callback eventually input as the argument to the entire function? As you can see, I'm a bit confused...

Was it helpful?

Solution

That code is confusing, as it returns a value that is never used.

That last line should look like this:

fn(messages);

Returning anything from the callback to the done method is pointless, as it will just be ignored.

The value for the parameter fn when you call the function should be a function, which will be called when the AJAX call is complete. That is the way that you pick up the result from the AJAX call.

Example; assume that the function is named xyz, you call it like:

xyz(function(msg) {
  // in here you can use the `msg` parameter to get the messages from the call
  alert(msg);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top