0

I'm using jQuery's $.when and .always deferred methods to retrieve a dataset from two different end points (I cannot change this).

I have an abstract method that looks like this:

function getData(reqUrl, reqData) {
    var reqType = 'GET';
    var contentType = 'application/json;charset=UTF-8';
    if(reqData){
        reqType = 'POST';
        contentType = 'application/x-www-form-urlencoded';
    }

    return $.ajax({
        url: reqUrl,
        type: reqType,
        data: reqData ? reqData : null,
        dataType: 'json',
        contentType: contentType
    });
}

I have two call to that function that look like this:

var req1 = getData('/path/to/endpoint1', {
          dir: 'asc',
          sort: 'name',
          results: 100,
          startIndex: 0
        });

var req2 = getData('/path/to/endpoint2');

I then pass both of those into a jQuery $.when and .always so that even if one fails, I can still proceed with the data I do get back.

$.when(req1, req2)
 .always(function(resp1, resp2) {
      console.log(resp1);
      console.log(resp2);
});

I am expecting resp1 to come back with a 200, and it does when I look at it in the Chrome dev tools. resp2 should throw a 404 at this point and it also does so in the Chrome dev tools.

However, when the two console.log statements get hit, resp1 is logging out an jqXhr object with a status of 404, and resp2 just logs the string literal "error".

If I remove resp2 from the $.when, then everything works as expected. That is to say that resp1 comes back with the data I expect.

If I remove resp1 from the $.when then everything works and I get the jqXhr object with the 404 status code.

But when I combine them, resp1 seems to get over written by resp2. I'm a bit at a loss since I have confirmed they work independently.

Joel Kinzel
  • 969
  • 2
  • 7
  • 19
  • 1
    If one fails, `$.when(…)` rejects, and `always` reports that – Bergi Jun 21 '16 at 20:31
  • So if I'm reading the documentation correctly: In the event of the master promise being rejected (due to the failed status of `resp2` in this case) `.always` will only get the jqXhr obj of the failed promise? Thanks for the clue. Feel free to make a full answer and I'll mark it as accepted. – Joel Kinzel Jun 21 '16 at 20:41
  • 1
    Yes, exactly. See the duplicate question for a solution (I won't answer here but you can upvote over there) – Bergi Jun 21 '16 at 20:47

0 Answers0