jQuery Deferred

Beginner
⏱️ 14 min read
📚 Updated: Jul 2026
🎯 18 Tutorials
Async API

What You’ll Learn

Asynchronous code runs in the background — AJAX calls, timers, animations. jQuery Deferred gives you a structured way to run code when those tasks succeed, fail, or update progress. This hub links to 18 Deferred method tutorials.

Deferred()

Create objects

Learn how to create Deferred objects and control asynchronous operations with flexibility.

done / fail

Success & error

Handle success and failure callbacks efficiently to manage the outcome of your async tasks.

always

Cleanup

Execute code after success or failure. Perfect for cleanup operations and final steps.

then

Chain steps

Chain multiple asynchronous steps together and pass results between them seamlessly.

promise

Read-only view

Work with a read-only promise interface for safer and more predictable code.

18 guides

Full index

Explore all 18 Deferred method tutorials in a structured and beginner-friendly learning path.

Introduction

jQuery Deferred is a powerful way to handle asynchronous operations in JavaScript. It provides a flexible API to manage tasks that may take time to complete, such as AJAX requests, animations, or custom functions.

It helps you write cleaner, more maintainable code by giving you better control over the flow of asynchronous tasks.

Why it matters?

Asynchronous operations are everywhere in modern web development. Deferred helps you coordinate those operations efficiently and predictably.

Key Highlights

Simplifies Asynchronous Code

Manage complex async flows with a simple and consistent API.

Better Control & Flexibility

Chain operations, handle success or failure, and track progress with ease.

Reliable Error Handling

Gracefully handle errors and keep your application stable.

Highly Extensible

Works well with other jQuery features and third-party plugins.

In short: Deferred makes it easier to work with asynchronous tasks, so you can focus on building great features instead of worrying about callback complexity.

📝 Syntax

Create a Deferred, attach handlers, and settle it:

jQuery
const dfd = $.Deferred();

dfd.done(function (data) {
  console.log("Success:", data);
}).fail(function (err) {
  console.error("Failed:", err);
}).always(function () {
  console.log("Cleanup runs either way");
});

// Later, when async work finishes:
dfd.resolve("Hello from Deferred");

Method groups

GroupExamplesPurpose
Factory$.Deferred()Create a new Deferred object
Handlersdone(), fail(), always()Register callbacks
Settlementresolve(), reject()Finish the async task
Chainingthen(), catch()Pipeline transforms and errors
Progressprogress(), notify()Interim status updates
Statusstate(), promise()Inspect or expose read-only access

⚡ Quick Reference

GoalMethod
Create a Deferred$.Deferred()
On successdfd.done(fn)
On failuredfd.fail(fn)
Cleanup either waydfd.always(fn)
Chain stepsdfd.then(doneFn, failFn)
Mark successdfd.resolve(value)
Mark failuredfd.reject(reason)
Check status (jQuery 3+)dfd.state() → pending | resolved | rejected
Share read-only accessdfd.promise()
Context

When to Use Deferred

Deferred is useful when you need better control, structure, and reliability for asynchronous operations in your application.

  1. Custom async APIs

    Wrap setTimeout, third-party SDKs, or Web APIs in a Deferred so your app can consume uniformly.

  2. AJAX requests

    Chain .done() / .fail() on $.ajax() without nested callbacks.

  3. Animation sequences

    Coordinate code that runs when effects complete or fail.

  4. Module boundaries

    Return promise() from a module so internals stay private.

  5. Progress UI

    Use notify() and progress() for upload bars or multi-step wizards.

Key benefit: Deferred gives you explicit control over success, failure, and progress—resulting in cleaner, more maintainable asynchronous code.

👀 Deferred Lifecycle

A Deferred moves through three states:

pending → resolve() → resolved → done() + always() run pending → reject() → rejected → fail() + always() run pending → notify() → still pending → progress() runs

Deferred Method Tutorial Index

Search by method name or browse by category. Each tutorial includes syntax, five try-it examples, and FAQs.

Getting Started

4 tutorials

Create Deferreds and attach the core success/failure listeners.

MethodDescriptionTutorial
jQuery.Deferred()Factory that creates a new Deferred object for custom async workflows.Open
done()Register a callback that runs when the Deferred resolves successfully.Open
fail()Register a callback that runs when the Deferred is rejected.Open
promise()Return a read-only promise so callers cannot resolve or reject.Open

Handlers & Chaining

5 tutorials

Register callbacks, chain transforms, and handle errors in pipelines.

MethodDescriptionTutorial
always()Register a callback that runs after resolve or reject — ideal for cleanup.Open
catch()Handle rejection at the end of a promise chain (like Promise.catch).Open
then()Chain success and failure handlers; return values flow to the next step.Open
pipe()Legacy filter/chain API — deprecated in jQuery 3+; use then() instead.Open
progress()Listen for interim progress updates from notify() or notifyWith().Open

Progress

2 tutorials

Report interim status before final resolve or reject.

MethodDescriptionTutorial
notify()Send a progress update while the Deferred is still pending.Open
notifyWith()Send progress with a custom this context and argument array.Open

State & Settlement

7 tutorials

Resolve, reject, inspect status, and bind context with With-methods.

MethodDescriptionTutorial
resolve()Settle the Deferred as successful and pass results to done() handlers.Open
resolveWith()Resolve with a custom this context and arguments in an array.Open
reject()Settle the Deferred as failed and pass reasons to fail() handlers.Open
rejectWith()Reject with a custom this context and arguments in an array.Open
state()Return "pending", "resolved", or "rejected" — preferred status check in jQuery 3+.Open
isResolved()Return true if the Deferred resolved (deprecated — prefer state()).Open
isRejected()Return true if the Deferred rejected (deprecated — prefer state()).Open

Examples Gallery

Include jQuery 3.7+ and open DevTools Console (F12) to run each snippet.

📚 Create & Listen

Build a Deferred and settle it manually.

Example 1 — Create and Resolve a Deferred

Simulate async work with setTimeout, then resolve with a result.

jQuery
function fetchGreeting() {
  const dfd = $.Deferred();

  setTimeout(function () {
    dfd.resolve("Hello, Deferred!");
  }, 500);

  return dfd.promise();
}

fetchGreeting().done(function (msg) {
  console.log(msg);
});

How It Works

The factory creates a Deferred; you return promise() so callers cannot call resolve themselves. Settlement happens inside your async function.

Example 2 — done(), fail(), and always()

Classic AJAX-style handlers for success, error, and shared cleanup.

jQuery
function loadData(shouldFail) {
  const dfd = $.Deferred();
  setTimeout(function () {
    if (shouldFail) {
      dfd.reject("Network error");
    } else {
      dfd.resolve({ id: 1, name: "Ada" });
    }
  }, 300);
  return dfd.promise();
}

loadData(false)
  .done(function (data) { console.log("Loaded:", data.name); })
  .fail(function (err) { console.error(err); })
  .always(function () { console.log("Request finished"); });
done() Tutorial

How It Works

always() runs after either branch — perfect for hiding loading spinners. Pass true to loadData to see the fail path instead.

📈 Chain & Encapsulate

Pipeline values and hide settlement from consumers.

Example 3 — Chain with then()

Transform resolved values through a pipeline — similar to native Promises.

jQuery
$.Deferred()
  .resolve(10)
  .then(function (n) { return n * 2; })
  .then(function (n) { return "Result: " + n; })
  .done(function (msg) { console.log(msg); });
then() Tutorial

How It Works

Each then() callback can return a new value that flows to the next step. Use the second argument or catch() for error handling in longer chains.

Example 4 — Expose promise() Only

Keep resolve/reject private inside a module; return a read-only promise.

jQuery
const Timer = (function () {
  const dfd = $.Deferred();

  setTimeout(function () {
    dfd.resolve("Timer done");
  }, 400);

  // Public API — no resolve/reject exposed
  return {
    onComplete: dfd.promise()
  };
})();

Timer.onComplete.done(function (msg) {
  console.log(msg);
});

// Timer.onComplete.resolve("hack"); // undefined — safe!

How It Works

promise() strips settlement methods. External code can listen but cannot change the outcome — a simple encapsulation pattern.

Example 5 — Inspect with state()

Check whether a Deferred is still pending or has settled (jQuery 3+).

jQuery
const dfd = $.Deferred();

console.log("Before:", dfd.state()); // pending

dfd.resolve("OK");
console.log("After resolve:", dfd.state()); // resolved

const dfd2 = $.Deferred();
dfd2.reject("Oops");
console.log("After reject:", dfd2.state()); // rejected
state() Tutorial

How It Works

state() replaces deprecated isResolved() / isRejected() with one clear string. A Deferred can only settle once — subsequent resolve/reject calls are ignored.

Use Cases

Real-world scenarios where this tool or approach can be applied to solve common problems efficiently.

1. AJAX Requests

Handle asynchronous HTTP requests without blocking the UI.

Example: Fetching data from APIs, submitting forms, loading content.

2. Animations

Coordinate complex animations sequentially or in parallel.

Example: Chaining animations, delaying effects, smooth transitions.

3. Custom APIs

Build and manage custom APIs with multiple asynchronous steps.

Example: Validations, data processing, multi-step workflows.

4. File Uploads

Track upload progress and handle success or failure scenarios.

Example: Uploading files, showing progress bars, retry on failure.

5. Sequential Workflows

Execute tasks in a specific order where each step depends on the previous one.

Example: Form wizards, step-by-step processes, data pipelines.

6. Delayed Execution

Run functions after a delay or at a specific time.

Example: Auto-save, notifications, timeouts, polling.

Pro Tip: These are just a few examples — explore and combine them to build powerful, responsive applications.

Advantages

Why reach for Deferred? Here’s what it brings to your async code.

  1. 1. Cleaner Organization

    Separate success, failure, and cleanup instead of one giant callback.

  2. 2. Better Error Handling

    Route failures to fail() or catch() consistently.

  3. 3. Promise Compatibility

    Integrates with jQuery AJAX and patterns familiar from native Promises.

  4. 4. Progress Support

    Report interim status with notify() — something basic callbacks lack.

Pro Tip: Combine these strengths — handle success, failure, and progress in one place for maintainable async flows.

Usage Tips

Follow these best practices to write clean, efficient, and maintainable code.

  1. 1. Start Small

    Begin with simple examples and gradually move to complex use cases.

  2. 2. Keep it Focused

    Use each feature for a specific purpose and avoid overcomplicating your code.

  3. 3. Chain Smartly

    Leverage chaining to write concise code, but keep it readable.

  4. 4. Handle Errors

    Always use .fail() or .catch() to handle errors gracefully.

  5. 5. Monitor Performance

    Use .progress() to provide feedback for long-running operations.

Pro Tip: Practice regularly and explore real-world examples to master these concepts faster!

Common Pitfalls

Avoid these common mistakes to write better, more reliable code.

  1. 1. Forgetting Error Handling

    Not handling errors can cause your application to break unexpectedly.

    → Always use .fail() or .catch() to handle errors gracefully.

  2. 2. Blocking the UI

    Long-running tasks or synchronous operations can freeze the UI.

    → Use deferred objects and asynchronous patterns to keep the UI responsive.

  3. 3. Overusing Callbacks

    Too many nested callbacks lead to “callback hell” and make code hard to read.

    → Use chaining and proper structure to keep your code clean and readable.

  4. 4. Not Resolving or Rejecting

    A deferred that is never resolved or rejected can leave your code in a pending state.

    → Always call resolve() or reject() in all code paths.

  5. 5. Ignoring Progress Updates

    Forgetting to report progress in long-running tasks can lead to a poor user experience.

    → Use .progress() to keep users informed about ongoing operations.

Pro Tip: Write small, test often, and review your code to catch issues early.

🧠 How Deferred Works

1

Create

$.Deferred() starts in the pending state with empty callback queues.

Factory
2

Register handlers

done, fail, always, and progress queue callbacks for later.

Listen
3

Settle

resolve or reject locks the state and drains the matching queues.

Settle
=

Responsive async code

Callbacks run in order, UI stays unblocked, and errors have a clear path.

Browser Support

jQuery Deferred ships with jQuery 1.5+ and is fully supported in jQuery 3.7.x. Methods like state() and catch() align with jQuery 3+. For greenfield projects, also consider native Promise — but Deferred remains essential when using jQuery AJAX and legacy plugins.

jQuery 1.5+

Deferred & Promise API

Available wherever jQuery runs — all modern browsers and IE 9+ with a supported jQuery build. Match your jQuery version to project requirements.

100% With jQuery
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 methods Universal

Bottom line: Safe for jQuery-based apps. Prefer state() and then() in jQuery 3+ code; treat pipe() as legacy.

Wrap Up

🎉 Conclusion

jQuery Deferred is a powerful tool for managing asynchronous tasks — from AJAX to animations to custom APIs.

Start with $.Deferred(), done(), resolve(), then explore chaining and progress as you grow.

Use the searchable index to open all 18 tutorials — each includes try-it labs and FAQs.

💡 Best Practices

✅ Do

  • Return promise() from public APIs
  • Use always() for shared cleanup
  • Check status with state()
  • Chain multi-step work with then()
  • Register handlers before settling

❌ Don’t

  • Expose the raw Deferred to callers
  • Call resolve and reject both
  • Duplicate cleanup in done and fail
  • Use pipe() in new jQuery 3 code
  • Memorize all 18 names at once

Key Takeaways

Knowledge Unlocked

Five things to remember about Deferred

Your gateway to 18 method tutorials.

5
Core concepts
02

done / fail

Success & error

Handlers
03

always

Either outcome

Cleanup
04

then()

Chain values

Pipeline
18 05

Index

Search all

Ref

❓ Frequently Asked Questions

A Deferred is a jQuery object that represents an asynchronous task. You register callbacks for success (done), failure (fail), cleanup (always), or progress, then settle it later with resolve() or reject(). It powers $.ajax() and custom async APIs.
A Deferred is read-write — you can resolve, reject, and notify. promise() returns a read-only Promise that consumers can listen to but cannot settle. Share the promise with callers; keep the Deferred private inside your module.
Both work. done() and fail() are explicit and great for beginners. then() chains transforms and errors in one pipeline — similar to native Promises. Prefer then() for multi-step pipelines; use done/fail/always for simple AJAX-style handlers.
In jQuery 3+, call state() — it returns "pending", "resolved", or "rejected". Older isResolved() and isRejected() still work but are deprecated.
Yes. jqXHR objects returned by $.ajax() implement the Deferred interface, so you can chain .done(), .fail(), .always(), and .then() directly on AJAX calls.
Read the overview, try the five examples, then open jQuery.Deferred() or always() from Getting Started. Use the search box to jump to any of the 18 method tutorials.

Did you Know? 🔉

You've been using Deferreds without realizing it! Every $.ajax() secretly hands you a Promise-like object — so you can chain .done() and .fail() right onto your calls. No $.Deferred() required. Sneaky, right? 😏

Start with always()

Learn how to run cleanup code whether an async task succeeds or fails.

always() 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.

10 people found this page helpful