1

I am practicing with JQuery .when() function and I receive unexpected results when I use .when with 2 functions that performs ajax calls.

For instance, for single function

$.when(getFolders(id)).then(function(folders) {
     /* return value is as expected */
});

Following is the content of folders in this case ,

enter image description here

However, in following case,

$.when(getFolders(idOfClickedFolder), getFiles(idOfClickedFolder))
   .then(function( folders, files ) {
      /* results formats are not similar here with above one */
});

content of folders is like below, an the actual Folder objects are located inside the first Object of response. I mean I can access the returned JSON object via folders[0].

enter image description here

Following is the getFolders function, getFiles is same as getFolders having different url for ajax.

function getFolders(rootId) {
    return $.ajax({
        url: '/FileManager/GetFolders/' + rootId,
        async: true,
        dataType: 'json'
    });
}

I am wondering why I am getting the results in two different format.

Thanks.

emre nevayeshirazi
  • 18,983
  • 12
  • 64
  • 81

1 Answers1

1

A jQuery AJAX Deferred always returns 3 arguments : data, textStatus, jqXHR. The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. (from $.ajax doc http://api.jquery.com/jQuery.ajax/ )

When you use $.when with 2 AJAX deffereds, these 3 arguments are in an array.

From the $.when() doc : http://api.jquery.com/jQuery.when/

$.when( $.ajax("test.aspx") ).then(function(ajaxArgs){ 
     alert(ajaxArgs[1]); /* ajaxArgs is [ "success", statusText, jqXHR ] */
});

If you want to create a custom AJAX Deferred returning only first argument, you can do :

// creating a new deferred
var myDfd = $.Deferred();

// execute AJAX query, and when the query is okay, resolve my deferred with only the res of the AJAX query
$.ajax({
   url: '/FileManager/GetFolders/' + rootId,
   async: true,
   dataType: 'json'
}).then(function(folders) {
   myDfd.resolve(folders);
});

// I can use my own Deferred
$.when(myDfd).then(function(folders) {
  // folders contains ajax response only
});
odupont
  • 1,946
  • 13
  • 16
  • thx for answer. When I use .when with single ajax call, it is not returning that 3 arguments. It only happens when there are 2 ajax calls inside .when. – emre nevayeshirazi Jul 12 '12 at 19:56
  • For a simple Ajax call, you don't need to use $.when(). This function is great when you want to wait multiple queries (or deferred). For one query, you can do `$.ajax().then(function(res) {})` or use the _success_ option. – odupont Jul 12 '12 at 20:00