1

I have a list of itens to pass through a function that returns a $.ajax() but the .done is getting called after the $.each is called, not after the inners ajax calls complete! What should I do?!?

Here is my code:

$.when(
    $.each(data, function (index, item) {
        GetReservation(
            item.UniqueId,
            apiRoot,
            //this is the 'success' function
            function (data2) {
                //do my stuff
            },
            //this is the 'error' function
            function (x, y, z) {
                if (x.status == 404) {
                    //OK, no reservations!
                }
            });
    })
).done(setButtons(box, c));
Leonardo
  • 10,737
  • 10
  • 62
  • 155

1 Answers1

5

$.each is not returning an array of promises as your code seems to be expecting. You should build an array of promises first then call $.when with your array:

var promises = [];

$.each(data, function (index, item) {
    // add promise to array
    promises.push(GetReservation(
        item.UniqueId,
        apiRoot,
        //this is the 'success' function
        function (data2) {
            //do my stuff
        },
        //this is the 'error' function
        function (x, y, z) {
            if (x.status == 404) {
                //OK, no reservations!
            }
        }
    ));
})

$.when.apply($, promises).done(function(){
  setButtons(box, c)
});
Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • problem persists... setButtons still getting called before GetReservation done... – Leonardo Apr 10 '14 at 16:30
  • I saw the problem immediately, setButtons was being invoked immediately and needed to be wrapped in a function. I've updated my example – Rob M. Apr 10 '14 at 16:31
  • Also, make sure your `GetReservation` function is returning the promise. – Rob M. Apr 10 '14 at 16:32
  • Without looking at more of your source code (specifically the `GetReservation` function, it's hard to say. Calling `$.when` in this manner will definitely work if you are using an array of promises, for example: `$.when.apply($, [$.get('example.html'), $.ajax({..})]).done(..)`. So assuming `GetReservation` is doing something like `return $.ajax(...)` it should be working. – Rob M. Apr 10 '14 at 16:56