JQuery Deferred: Rejecting a promise from an inline filter

Fyi, I'm just starting to learn jQuery promises, so I'm a little confused here.

Anyway, I have an AJAX request that I want to reject from a filter made based on the content of the response:

return doAJAXRequest().then(function (data) { if (data.responseText == "YES") { return doOtherAJAXRequest(); } else { this.reject(data); } }); 

This did not work as I expected:

 Uncaught TypeError: Object #<Object> has no method 'reject' 

How can I make this promise unsuccessful based on his answer? Is it possible? Or am I just confused about what needs to be done here?

+22
jquery jquery-deferred
Jul 23 '13 at 1:37
source share
1 answer

In jQuery (unlike some other libs), converting a promise from an “allowed” state to a “rejected” state is a little verbose, requiring the explicit creation and rejection of a new Pending one.

 function foo() { return doAJAXRequest().then(function (data, textStatus, jqXHR) { if (data.responseText == "YES") { return doOtherAJAXRequest(data); } else { return $.Deferred().reject(jqXHR, data, 'Not YES').promise(); } }); ) 

Here the promise is returned if data.responseText !== "YES" imitates a (partially) failed ajax request, but still allows data to be transmitted. This is (probably) important for the downstream .fail() handler, which should handle both real ajax failures and the underserved success conditions, not knowing which one happened until it reads errorThrown .

 foo().fail(function(jqXHR, textStatus, errorThrown) { if(errorThrown == 'Not YES') { //transmogrified success var data = textStatus; ... } else { //genuine ajax failure ... } }); 

It is usually easier to pass data this way, rather than retrying it from the jqXHR object. This is especially true for JSON-encoded data that would otherwise need to be decoded a second time in the fault handler.

+31
Jul 24. '13 at 17:04 on
source share



All Articles