jQuery Deferred rejectWith() Method

Beginner
7 min read
Updated: Oct 2026
5 examples
Live preview

What Is rejectWith()?

deferred.rejectWith(context [, args]) settles a Deferred as rejected (since jQuery 1.5) and runs fail callbacks with this set to context. Optional args is an array whose values become the callback parameters. It returns the same Deferred for chaining.

Remember
deferred.rejectWith(context [, argsArray])

context  → this inside fail callbacks
args     → array → separate parameters

reject("msg")
rejectWith(obj, ["msg"])   // same args, custom this

pair with: resolveWith / notifyWith
keep private; return promise()
NeedUse
Fail with custom thisdfd.rejectWith(obj, [reason])
Fail without caring about thisdfd.reject(reason)
Success with custom thisdfd.resolveWith(obj, [value])

How to Use rejectWith()

Pick a context object, wrap failure values in an array, then reject.

  1. Create a Deferred (keep it private in your helper).
  2. Attach fail() handlers that use this if needed.
  3. On failure, call rejectWith(context, [arg1, arg2, …]).
  4. Return promise() to callers so they cannot settle the Deferred.
PieceRequired?Role
contextYesBecomes this in fail callbacks
argsOptionalArray of values passed as parameters
Return—Same Deferred (chainable)
Since—jQuery 1.5

Pseudocode

Pseudocode
rejectWith(context, argsArray):
    if already settled: return
    state = "rejected"
    remember context + argsArray
    for each fail handler (add order):
        call handler with this = context
        and parameters = values from argsArray

reject(a, b) ≈ rejectWith(defaultThis, [a, b])
// difference: you choose context with rejectWith

Cheat Sheet

Keep these facts handy when failing with a custom this.

TopicDetail
Syntaxdeferred.rejectWith(context [, args])
args shapeArray → spread as callback parameters
Triggersfail(), rejection branch of then(), always()
vs reject()Same settle; rejectWith sets this
FamilyresolveWith, notifyWith
OnceSettles once; later settle calls ignored
SincejQuery 1.5

Live Preview

See how rejectWith() sets this and spreads an args array.

Browser demo of deferred.rejectWith — same idea as the examples below.

Result
this.id → uploader
reason → timeout

/* context becomes this in fail() */

jQuery Examples

Short, copy-ready snippets. Open the browser console, or use Try It Yourself for a live editor.

Example 1 — Custom this in fail()

Pass a context object so the fail handler can read this.id.

jQuery
var ctx = { id: "uploader" };
var dfd = $.Deferred();

dfd.fail(function (reason) {
  console.log(this.id + ": " + reason);  // uploader: timeout
});

dfd.rejectWith(ctx, ["timeout"]);
Try It Yourself

How It Works

  1. Define context. ctx holds an id the handler needs.
  2. Attach fail. The callback uses this.id and the reason arg.
  3. Reject with context. rejectWith(ctx, ["timeout"]) sets this.
  4. Log together. Output combines object id and error text.

Example 2 — Multiple Values in the Args Array

Put several failure values in an array; they become separate parameters.

jQuery
var dfd = $.Deferred();

dfd.fail(function (code, message) {
  console.log(code + ": " + message);  // 404: Not found
});

dfd.rejectWith(null, [404, "Not found"]);
Try It Yourself

How It Works

  1. Plan parameters. Fail expects (code, message).
  2. Wrap in an array. [404, "Not found"] is required for rejectWith.
  3. Context can be null. When you only need args, pass null as context.
  4. Spread happens. jQuery calls the handler with two separate args.

Example 3 — reject() vs rejectWith()

Same failure values; only rejectWith controls this.

jQuery
var ctx = { tag: "A" };

$.Deferred().fail(function (msg) {
  console.log("reject this.tag:", this.tag);  // undefined (usually)
}).reject("oops");

$.Deferred().fail(function (msg) {
  console.log("rejectWith:", this.tag, msg);  // A oops
}).rejectWith(ctx, ["oops"]);
Try It Yourself

How It Works

  1. Plain reject. Args are fine; this is not your object.
  2. rejectWith. Same message, but this is ctx.
  3. Choose by need. Use reject for simple reasons; rejectWith when methods need this.
  4. Args array. Remember the brackets: ["oops"], not a bare string as the second param.

Example 4 — Late fail() After rejectWith()

Handlers added after rejection still run with the stored context and args.

jQuery
var ctx = { id: "job-7" };
var dfd = $.Deferred();

dfd.rejectWith(ctx, ["stopped"]);

dfd.fail(function (reason) {
  console.log(this.id + " → " + reason);  // job-7 → stopped
});
Try It Yourself

How It Works

  1. Reject first. Context and args are stored; state is rejected.
  2. Attach fail late. Official rule: it runs immediately.
  3. Same binding. this is still ctx.
  4. Same args. You still get "stopped".

Example 5 — rejectWith Behind promise()

Only the owner rejects with context; callers listen on the Promise.

jQuery
function runTask(service, ok) {
  var dfd = $.Deferred();
  setTimeout(function () {
    if (ok) dfd.resolveWith(service, ["done"]);
    else dfd.rejectWith(service, ["failed"]);
  }, 200);
  return dfd.promise();
}

var svc = { name: "backup" };
runTask(svc, false).fail(function (err) {
  console.log(this.name + ": " + err);  // backup: failed
});
Try It Yourself

How It Works

  1. Private Deferred. Only runTask can settle.
  2. rejectWith(service, …). Fail handlers see this === service.
  3. Return Promise. Callers cannot call rejectWith themselves.
  4. Listen with fail. Logs backup: failed.

Edge Cases & Pitfalls

Check these before using rejectWith() in real projects.

array

Second argument must be an array

Write rejectWith(ctx, ["msg"]), not rejectWith(ctx, "msg"). A bare string is not spread as one parameter the way you might expect.

arrow

Arrow functions ignore this

Arrow fail handlers do not get the rejectWith context. Use a normal function when you need this.

once

Settles only once

After resolve/reject/*With, further settle calls are ignored.

owner

Keep settle methods private

Return promise() so callers can attach fail but cannot call rejectWith.

Browser Support

deferred.rejectWith() needs jQuery 1.5+ loaded. It works across jQuery 1.5–3.x alongside reject(), resolveWith(), and notifyWith().

✓ jQuery 1.5+

deferred.rejectWith()

Works in Chrome, Firefox, Safari, and Edge when jQuery 1.5+ is loaded. Use it when fail handlers need a specific this.

100% With jQuery 1.5+
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
rejectWith() Universal

Bottom line: Safe wherever jQuery Deferreds exist. Prefer reject() when you do not need a custom this.

Performance Notes

ApproachCostBest for
reject(args…)Slightly simplerNo custom this
rejectWith(ctx, arr)Same order of costMethod-style fail handlers
Huge args arraysCopied to handlersKeep payloads small

Prefer rejectWith for correct this binding, not for speed. The expensive part is usually your fail handlers, not the settle call.

Key Takeaways

  • Role: reject with a chosen this and an args array.
  • Args: second parameter is an array that spreads to fail handlers.
  • Family: matches resolveWith / notifyWith.
  • Safety: owner-only; expose promise() to callers.

One line: rejectWith(ctx, [args…]) fails the Deferred and binds this for fail handlers.

Frequently Asked Questions

rejectWith(context, args) settles the Deferred as rejected. Fail callbacks from fail() or then() run with this set to context, and parameters taken from the optional args array.
reject(...values) passes arguments directly. rejectWith(ctx, [a, b]) lets you choose this and wrap values in an array — the same pattern as resolveWith() and notifyWith().
An optional array (or array-like) such as ["timeout"] or [404, "Not found"]. jQuery spreads those values as separate parameters to each fail callback.
When fail handlers are methods on a widget or service object and need this to point at that object — especially inside timers or nested callbacks where this would otherwise be lost.
No. A Deferred settles once. After resolve(), later rejectWith() is ignored.
Usually no. Keep the Deferred private and return promise() so outside code can listen with fail/done but cannot settle the operation.

Next: deferred.resolve()

Learn how to settle a Deferred successfully and run done handlers.

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.

9 people found this page helpful