Search code examples
jqueryjquery-deferredjqxhr

What does 'rejected' mean for Deffered objects other than jqXHRs?


From deferred.fail() page :

Description: Add handlers to be called when the Deferred object is rejected.

and the exmple:

$.get("test.php")
.done(function(){ alert("$.get succeeded"); })
.fail(function(){ alert("$.get failed!"); });

As we know, we can create var someObject = $.Deferred();

My questions:

  • How can we 'Reject' a Deferred if it's not a jqXHR?

  • How to implement deferred.fail() for Deferred objects other than jqXHR?

Thanks.

Yes, I know my English is bad.


Solution

  • A deferred object is rejected when either .reject() or .rejectWith() is called on it.

    Here's an example:

    var deferred = $.Deferred();
    deferred
      .done(function() { console.log('done') })
      .fail(function() { console.log('failed') });
    
    deferred.resolve(); // <-- will write 'done' to console
    deferred.reject();  // <-- will write 'failed' to console
    

    You can use deferreds to make asynchronous functions behave like $.get() does. For example setTimeout:

    function MyTimeout() {
      var deferred = $.Deferred();
    
      setTimeout(function() {
        // as a demo, this will reject the deferred half the time
        if (Math.random() < 0.5)
          deferred.reject();
        else
          deferred.resolve();
      }, 2000);
      return deferred.promise();
    }
    
    MyTimeout()
      .done(function() { console.log('done') })
      .fail(function() { console.log('failed') });
    

    The last statement can also be written as:

    MyTimeout().then(
      function() { console.log('done') },
      function() { console.log('failed') }
    );