Question

I'm doing an ajax call that can return {status: ok} or {status: error} along with other data.

I'd like to do a .then(doneFilter) that would check the status member and then modify things such that the Deferred now will resolve only if the status was ok.

I'm not sure of the syntax for that. Could someone write me an example?

Was it helpful?

Solution 2

I think that you want to modify the ajax deferred itself to trigger different callbacks based upon the return state. You can't because Promise objects can be resolved only once. Look at this example:

var fai = $.Deferred();
fai.then(function () {
    fai.reject();
    console.log(fai.state());
}).done(function () {
    console.log(fai.state()); 
});
fai.resove();

http://jsfiddle.net/ExplosionPIlls/QreYY/

The chain of events would be calling .resolve, and then the .then callback. .then calls .reject. However, if you run this you will see that the state after the .reject call is still "resolved," and the .done callback gets triggered.

That is to say if your ajax request succeeds it will already be set to the .resolved state and you can't undo that.

Instead, you can do something like this, which I think is simpler anyway:

$.ajax(...).done(function (json) {
   if (json && json.status == 'ok') {
      //handle success right here
   }
   else {
      //handle failure right here
   }
});

OTHER TIPS

Here's a typical example:

/*  Returns a deferred object.  It is resolved if the ajax call succeeded, and
    is rejected otherwise.
*/
function doAjaxThing() {
    var df = $.Deferred();
    $.ajax('http://someurl.org/path/whatever').done( function(data) {
        if('test for success here')
            df.resolve();
        else
            df.reject();
    }).fail( function() {
        df.reject();
    });

    return df;  
}

doAjaxThing().then( 
    function() { 'success!'; },
    function() { 'failure.'; }
);

It is important that you handle not only the success case, but also the failure cases. And there are two ways your ajax call can fail: either the request returns {status: error} or the request itself fails because of some kind of server error.

You have other options available to you as well. You can pass data from your resolve/reject calls to your handlers. You can also use acceptWith() and rejectWith() to pass context (a this object) to your handlers as well.

I suggest you read the deferred object documentation if you haven't already.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top