How to Reject a jQuery Deferred Object

In jQuery, managing asynchronous workflows requires controlling the lifecycle of a Deferred object, transitioning it from a pending state to either resolved or rejected. This guide explains how to properly reject a jQuery Deferred object using the built-in reject() and rejectWith() methods, how to pass error arguments to failure callbacks, and how to verify the object's terminal state.

The deferred.reject() Method

The primary way to reject a jQuery Deferred object is by calling its .reject() method. Invoking this method transitions the Deferred from the "pending" state to the "rejected" state and immediately executes any failure callbacks attached via .fail(), .then(), or .always().

You can pass optional arguments to .reject(), which are then forwarded to the fail callbacks:

// Initialize a new Deferred object
var deferred = $.Deferred();

// Attach a failure callback
deferred.fail(function(errorMessage, errorCode) {
    console.error("Failed:", errorMessage, "Code:", errorCode);
});

// Reject the Deferred object with arguments
deferred.reject("Operation timed out", 408);

The deferred.rejectWith() Method

If you need to define a specific execution context (this) for the fail callbacks, use .rejectWith(). This method accepts the context object as the first argument, followed by an optional array or arguments object containing the parameters passed to the callbacks.

var deferred = $.Deferred();

var errorContext = {
    service: "AuthenticationService",
    timestamp: Date.now()
};

deferred.fail(function(reason) {
    // 'this' refers to errorContext
    console.error("Error in " + this.service + ": " + reason);
});

// Reject with a custom context
deferred.rejectWith(errorContext, ["Invalid credentials"]);

Key Considerations

  • State Immutability: A Deferred object can only change its state once. Once marked as rejected (or resolved), subsequent calls to .resolve(), .reject(), .resolveWith(), or .rejectWith() are ignored.
  • Checking State: You can inspect the current state of a Deferred object at any time using deferred.state(). Once rejected, this method returns the string "rejected".
  • Promise Objects: If you expose a Promise using deferred.promise(), note that promises are read-only. You must reject the underlying Deferred instance, not the exposed promise, as promises lack the .reject() method by design.