jQuery Deferred rejectWith() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Failure + context

What You’ll Learn

The rejectWith() method settles a Deferred as failed like reject(), but lets you set this inside fail() callbacks and pass arguments as an array. This tutorial covers syntax, five examples, comparisons with reject() and resolveWith(), and when custom context matters for error handling.

01

Syntax

rejectWith(ctx, args)

02

context

Sets this

03

args

Array of values

04

fail()

Receives errors

05

vs reject

Context control

06

Since 1.7

With Deferred API

Introduction

Error handlers often need to update a specific UI widget, form view, or logging service. Inside a plain fail() callback, this may not point where you expect — especially after setTimeout, AJAX callbacks, or nested functions. rejectWith(context, args) solves that by binding this to your chosen object when the Deferred settles as rejected.

It mirrors the With family: resolveWith() for success, rejectWith() for failure, and notifyWith() for interim progress — all with the same context-and-array pattern.

Understanding the rejectWith() Method

rejectWith() is part of jQuery’s Deferred Object API (since jQuery 1.7). Calling deferred.rejectWith(context, args) locks the Deferred in the rejected state and invokes every fail(), catch(), and rejection branch of always() handler with this set to context and parameters taken from the args array.

Unlike reject(), which passes values directly with default this binding, rejectWith() gives you explicit control over both the callback context and how multiple arguments are delivered.

💡
Beginner Tip

Register fail() handlers before calling rejectWith() so you see the flow clearly. Handlers added after rejection still run immediately (jQuery queues them), but attaching first makes tutorials and debugging easier.

📝 Syntax

General form of deferred.rejectWith:

jQuery
deferred.rejectWith( context, args )

Parameters

  • context — object used as this when each fail() callback runs.
  • args — array or array-like object whose values are passed as separate arguments to failure handlers (e.g. ["Network error"] or [404, "Not found", "ERR_404"]).

Return value

  • Returns the same Deferred object (already settled as rejected).

Minimal example

jQuery
const errorView = {
  source: "Login form",
  show: function (message) {
    console.error(this.source + ":", message);
  }
};

const dfd = $.Deferred();

dfd.fail(function (message) {
  this.show(message);
});

dfd.rejectWith(errorView, ["Invalid credentials"]);

⚡ Quick Reference

GoalCode
Reject with custom thisdfd.rejectWith(ctx, [err])
Simple rejection (default this)dfd.reject(err)
Listen for failuredfd.fail(fn)
Success with same context patterndfd.resolveWith(ctx, [result])
Multiple rejection argsdfd.rejectWith(ctx, [status, msg, code])

📋 rejectWith() vs reject() vs resolveWith()

Three related methods — contextual failure, simple reject, and contextual success.

rejectWith()
ctx + args[]

Failure + this

reject()
direct args

Simpler failure

resolveWith()
ctx + args[]

Final success

State
rejected

Locks after call

Examples Gallery

Each example shows how rejectWith() binds this for failure handlers. Use the Try-it links to run them interactively.

📚 Getting Started

Bind failure callbacks to an error handler object with an explicit context.

Example 1 — Failure with an Error Handler Object

Pass an error reporter as context so this.source works inside fail().

jQuery
const errorHandler = {
  source: "Payment API",
  report: function (message) {
    console.error(this.source + " failed:", message);
  }
};

const dfd = $.Deferred();

dfd.fail(function (message) {
  this.report(message);
});

dfd.rejectWith(errorHandler, ["Card declined"]);
Try It Yourself

How It Works

rejectWith(errorHandler, [message]) sets this to errorHandler before invoking fail handlers — no manual .bind() required.

Example 2 — Form View Shows Validation Errors

A form view object owns the DOM update logic; failure handlers call its methods via this.

jQuery
const formView = {
  formId: "#signup-form",
  showErrors: function (errors) {
    console.log("Form " + this.formId + " errors:", errors.join(", "));
  }
};

const dfd = $.Deferred();

dfd.fail(function (errors) {
  this.showErrors(errors);
});

const validationErrors = ["Email is required", "Password too short"];
dfd.rejectWith(formView, [validationErrors]);
Try It Yourself

How It Works

Encapsulating UI logic on a context object keeps failure handlers thin — they delegate to this.showErrors() with the correct form reference.

📈 Practical Patterns

Compare with plain reject(), pass rich error tuples, and reject from async callbacks safely.

Example 3 — rejectWith() vs reject()

Without rejectWith(), this inside fail() is not the handler object.

jQuery
const logger = {
  tag: "AUTH",
  log: function (msg) {
    return this.tag + ": " + msg;
  }
};

const dfdPlain = $.Deferred();
dfdPlain.fail(function (msg) {
  console.log("plain reject →", typeof this.tag, msg);
});
dfdPlain.reject("Session expired");

const dfdWith = $.Deferred();
dfdWith.fail(function (msg) {
  console.log("rejectWith →", this.log(msg));
});
dfdWith.rejectWith(logger, ["Session expired"]);
Try It Yourself

How It Works

Plain reject() does not set this to your logger. rejectWith(logger, [msg]) does — the reason the With methods exist.

Example 4 — Multiple Rejection Arguments in an Array

Pass HTTP-style error tuples — fail() receives them as separate parameters.

jQuery
const apiClient = {
  name: "Users API",
  onHttpError: function (status, message, code) {
    console.log(this.name + ":", status, message, "(" + code + ")");
  }
};

const dfd = $.Deferred();

dfd.fail(function (status, message, code) {
  this.onHttpError(status, message, code);
});

dfd.rejectWith(apiClient, [503, "Service unavailable", "ERR_503"]);
Try It Yourself

How It Works

Wrap multiple values in the second argument array. jQuery spreads them into your callback — same pattern as reject(503, "...", "ERR_503") but with controlled this.

Example 5 — Reject from an Async Callback with Context

Inside setTimeout, pass the service object explicitly instead of relying on lost this.

jQuery
const uploadService = {
  label: "Photo upload",
  handleFailure: function (reason) {
    console.error(this.label + " aborted:", reason);
  }
};

const dfd = $.Deferred();

dfd.fail(function (reason) {
  this.handleFailure(reason);
});

setTimeout(function () {
  const uploadOk = false;

  if (uploadOk) {
    dfd.resolveWith(uploadService, ["Upload complete"]);
  } else {
    dfd.rejectWith(uploadService, ["Network timeout"]);
  }
}, 400);
Try It Yourself

How It Works

Inside timers, never rely on bare this. Pass uploadService as context so failure handlers can call this.handleFailure() reliably.

🚀 Use Cases

  • Form validation — bind failure to a form view that renders field errors in the DOM.
  • API error reporting — pass an HTTP client or logger as this with status codes and messages.
  • Widget-level failures — let a widget object handle its own error UI when async work fails.
  • Deferred chains — reject at any stage with consistent context for downstream fail() handlers.
  • Consistent With-methods — use the same context for notifyWith(), resolveWith(), and rejectWith() in one workflow.

🧠 How rejectWith() Invokes Failure Handlers

1

Register

dfd.fail(fn) queues handlers expecting failure notifications.

Listen
2

rejectWith

jQuery sets this = context, spreads args, and locks state to rejected.

Settle
3

Handlers run

fail(), catch(), and rejection always() callbacks execute once.

Notify
=

Context preserved

Failure handlers can call methods on the same controller object used during the async task.

📝 Notes

  • The args parameter must be array-like — use [message] even for a single argument.
  • rejectWith() does not run done() — only failure and always() handlers.
  • After rejection, further rejectWith() or resolveWith() calls are ignored.
  • Prefer explicit context objects over bare this inside async callbacks.
  • Consumers holding only a promise() cannot call rejectWith() — only the Deferred owner settles the outcome.

Browser Support

deferred.rejectWith() has been available since jQuery 1.7 alongside reject(), resolveWith(), and the full Deferred API.

jQuery 1.7+

jQuery Deferred.rejectWith()

Supported in jQuery 1.7+, 2.x, and 3.x wherever jQuery Deferred runs. Part of the jQuery-specific settlement API — not in native Promises.

100% With jQuery loaded
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
deferred.rejectWith() Universal

Bottom line: Use when fail() handlers need a stable this reference. For simple error strings without context, reject() is enough.

🎉 Conclusion

The deferred.rejectWith() method combines failure settlement with explicit context binding. Pass your error handler or view as the first argument, wrap callback parameters in an array, and let fail() handlers use this naturally.

Next, explore resolve() for the success counterpart, or review fail() for the listener side of rejection handling.

💡 Best Practices

✅ Do

  • Pass a stable context object (view, widget, logger)
  • Wrap arguments in an array: [err] or [status, msg]
  • Register fail() before rejecting when teaching or debugging
  • Reuse the same context for progress, success, and failure in one flow
  • Pass structured error data (status, message, code) when useful

❌ Don’t

  • Rely on this inside setTimeout without rejectWith
  • Pass a raw value instead of an array as the second argument
  • Call rejectWith after the Deferred already settled
  • Confuse rejectWith (owner settles) with fail() (listener registers)
  • Use rejectWith when plain reject() and closure variables suffice

Key Takeaways

Knowledge Unlocked

Five things to remember about rejectWith()

Failure settlement with controlled this binding.

5
Core concepts
🔗 02

this

= context

Binding
📦 03

args

Array-like

Params
04

Rejected

Final state

State
With 05

Family

resolveWith too

Pattern

❓ Frequently Asked Questions

rejectWith(context, args) settles the Deferred as rejected. It triggers fail(), catch(), and the rejection branch of always() handlers, with this set to context and parameters spread from the args array.
reject(...values) passes arguments directly with default this binding. rejectWith(ctx, [a, b]) lets you choose this and wrap multiple values in an array — the same pattern as resolveWith() and notifyWith().
args must be an array or array-like object (e.g. [message] or [404, "Not found", "ERR_404"]). jQuery spreads those values as separate parameters to your fail() callback.
Use it when fail() handlers are methods on a UI widget, error reporter, or service object and you want this to refer to that object — especially inside setTimeout or AJAX callbacks where this would otherwise be lost.
No. A Deferred settles once. If it already resolved, a later rejectWith() is ignored. Likewise, resolveWith() after rejection has no effect.
Yes. resolveWith(context, args) settles with success using a custom this; rejectWith(context, args) settles with failure; notifyWith(context, args) sends interim progress — all share the same context-and-array pattern.
Did you know?

jQuery’s With methods (notifyWith, resolveWith, rejectWith) predate widespread use of arrow functions and lexical this. They let legacy jQuery code pass object context explicitly — the same problem modern code often solves with closures or class fields.

Continue to resolve()

Learn how to mark a Deferred as successfully completed.

resolve() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful