0

I've got some code which makes requests to two different files on my web server, and I'd like to take some action after they're done, leveraging deferreds:

var url = 'testDataRoot.json',
    folderUrl= 'Content/testData.json';

var root = $.ajax({
    url: url,
    type: 'GET',
    dataType: 'json'
})

var folder = $.ajax({
    url: folderUrl,
    type: 'GET',
    dataType: 'json'
})

function getBiggest(arr) {
    arr.sort(function(a,b) {
        return a < b;
    })
    return arr[0];
}

$.when takes a list/array of deferred:

$.when([root,folder]).then(function(args){
    console.log(args); // promise array
    console.log(args[0]); // first promise
    console.log(args[0]['responseText']); // this has a value in the two previous lines yet undefined here, why?
});

I'd like to call getBiggest on the response from each deferred. I'd like a solution that would work for two deferreds, or 200. What's the most extensible way to accomplish this?

ntzm
  • 4,663
  • 2
  • 31
  • 35
wootscootinboogie
  • 8,461
  • 33
  • 112
  • 197
  • 3
    `$.when` doesn't take an array, it accepts a variable number of arguments. What happens is actually that `$.when` revolves immediately with the array as value. Check its documentation, especially the examples http://api.jquery.com/jquery.when/. The result of each promise is passed as argument to the callback. – Felix Kling May 13 '14 at 15:34
  • 1
    In addition, `getBiggest` is buggy and doesn't work. – Jon May 13 '14 at 15:35
  • @Jon could you elaborate, please? – wootscootinboogie May 13 '14 at 15:42
  • 2
    The comparison function you pass to `.sort` has to return 0 if both values are equal, a negative number if the first value is "smaller", and a positive number if it is "bigger". It is not supposed to retune a Boolean. – Felix Kling May 13 '14 at 15:53
  • Does the "duplicate" solve your issue or is this still a problem? If it is, have you considered `.then` on each promise? – Benjamin Gruenbaum May 13 '14 at 16:19

0 Answers0