0

The following piece of code, which calls a service using jQuery's getJSON, without the useJsonp section, worked fine for me for a long time. Then, there was a need to support JSONP and the if (useJsonp) condition was added. This also works fine, until the HTTP request fails. When I'm failing it (using Fiddler) with an 404 response, none of the callback (.done nor .fail is being called). When the request doesn't fail, I get to the .done callback.

function getData(url){
    var dfd = $.Deferred();
    if (useJsonp) {
        url += '&callback=?';
    }
    $.when($.getJSON(url))
        .done(function (dataObj) {
            if (!dataObj || dataObj.Status === 'failed') {
                dfd.reject(dataObj);
            }
            else {
                doSomething(dataObj);
                dfd.resolve(dataObj);
            }
        })
        .fail(function (jqXHR) {
            dfd.reject(jqXHR);
        });
    return dfd.promise();
};

Why is that? What can I do to make the callbacks called?

Thanks

Haji
  • 1,715
  • 7
  • 25
  • 41
  • WTH are you doing there? `$.getJSON` does already return a promise, `$.when()` does already return a promise, there is absolutely no reason to use `$.Deferred()`. Just `return $.getJSON(useJsonp?url+'&callback=?':url)` is enough. – Bergi Mar 03 '14 at 12:04
  • Thanks @Bergi - I edited the code to demonstrate that even if the getJSON was successful, I might need to reject it. So I can just call `return $.getJSON(...)`, I need to do something and then return the promise. This entire code is called somewhat like this: `$.when(getData(url)).done(...).fail(...)`. – Haji Mar 04 '14 at 12:10
  • OK, still you should use [`then`](http://api.jquery.com/deferred.then/) (like [this](http://stackoverflow.com/q/10843297/1048572)), instead of [manually constructing deferreds](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns#wiki-the-deferred-anti-pattern) – Bergi Mar 04 '14 at 13:23

2 Answers2

0

$.when closing bracket is mising, is it because of that, please try,other code is by far correct. This it the way it is to be achieved.

var dfd = $.Deferred();
if (useJsonp) {
    url += '&callback=?';
}
$.when($.getJSON(url))
    .done(function (dataObj) {
        dfd.resolve(dataObj);
    })
    .fail(function (jqXHR) {
        dfd.reject(jqXHR);
    }));
return dfd.promise();
Ankit Zalani
  • 3,068
  • 5
  • 27
  • 47
0

For jsonp requests I do the following:

$.ajax(url, {
    dataType: useJsonp ? "jsonp" : undefined,
    success: function(result) {
        console.log(result);
        alert("It worked!");
    },
    error: function(result) {
        console.log(result);
        alert("It didn't work!");
    }
});
Potassium Ion
  • 2,075
  • 1
  • 22
  • 39