Using Deferred and Promises in jQuery

Tutorial 5 of 5

Using Deferred and Promises in jQuery

Introduction

Goal

In this tutorial, our main goal is to introduce you to Deferred and Promises in jQuery, powerful tools that help manage asynchronous operations. These constructs allow you to create efficient, responsive, non-blocking web applications.

Learning Objectives

By the end of this tutorial, you will be able to:
- Understand the concept of Deferred and Promises in jQuery
- Use Deferred and Promises to manage asynchronous operations
- Apply best practices when working with Deferred and Promises

Prerequisites

Before starting, you should have a basic knowledge of:
- HTML
- JavaScript
- jQuery

Step-by-Step Guide

Deferred and Promises in jQuery are used to handle asynchronous operations like AJAX requests. They provide a way to react to the completion or failure of asynchronous operations.

A Deferred object in jQuery represents a unit of work that will be completed later, often asynchronously. It can report progress and failure or success states, and can have multiple callbacks attached to handle these outcomes.

A Promise is an object that represents a value which may not be available yet. It's a proxy for a value not necessarily known when the promise is created.

Example

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

// Add handlers to be called when Deferred object is resolved, rejected or still in progress
deferred
  .done(function() { console.log("Deferred object has been resolved!"); })
  .fail(function() { console.log("Deferred object has been rejected!"); })
  .progress(function() { console.log("Deferred object is still in progress..."); });

// Resolve the Deferred object
deferred.resolve();

Code Examples

Example 1: Using Deferred with AJAX

// Use $.ajax() to load data.json file
var deferred = $.ajax({ url: "/data.json" });

// Use the done() function to add a callback that will be executed when the AJAX request succeeds
deferred.done(function(data) {
  console.log("Data loaded successfully!");
  console.log(data);
});

// Use the fail() function to add a callback that will be executed if the AJAX request fails
deferred.fail(function() {
  console.log("Failed to load data!");
});

Example 2: Using Promises with AJAX

// Create a function that returns a Promise
function getData() {
  return $.ajax({ url: "/data.json" });
}

// Call the function and use the then() function to add callbacks
getData()
  .then(
    function(data) {
      console.log("Data loaded successfully!");
      console.log(data);
    },
    function() {
      console.log("Failed to load data!");
    }
  );

Summary

In this tutorial, we've learned about Deferred and Promises in jQuery and how they can be used to manage asynchronous operations. These are powerful tools that can make your code more readable and maintainable when dealing with asynchronous events.

For further learning, I recommend exploring the official jQuery documentation on Deferred and Promises.

Practice Exercises

Exercise 1

Create a Deferred object, add a done and fail callback, and then resolve the Deferred object.

Exercise 2

Create a function that returns a Promise. Call this function and add a then callback.

Solutions

// Exercise 1
var deferred = $.Deferred();
deferred
  .done(function() { console.log("Done!"); })
  .fail(function() { console.log("Fail!"); });
deferred.resolve();

// Exercise 2
function getData() {
  return $.ajax({ url: "/data.json" });
}
getData().then(function(data) { console.log(data); });

Keep practicing, and don't hesitate to refer back to this guide or the jQuery documentation as needed. Happy coding!