0Pricing
jQuery Academy · Lesson

Handling Multiple Asynchronous Tasks

Master the art of coordinating several independent or dependent asynchronous tasks, ensuring proper execution order and error handling across all operations.

Handling Multiple Asynchronous Tasks is a free jQuery Academy lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the jQuery Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Coordinate Async Tasks?

In web development, many operations are asynchronous. This means they don't happen instantly or in a strict sequence. Think of fetching data from a server, loading images, or running animations.

When your application needs to do multiple of these tasks at once, or in a specific order, you need a way to coordinate them effectively. This lesson will show you how!

The Challenge of Multiple Tasks

Imagine you need to load a user's profile and their latest notifications. Both are separate server requests.

  • How do you know when both are finished?
  • What if one fails?
  • What if one depends on the other (e.g., getting notifications for a specific user ID found in the profile)?

Without proper coordination, your UI might show incomplete data or break entirely.

Introducing `$.when()` for Parallel

jQuery's $.when() is a powerful tool for coordinating multiple independent asynchronous operations. It takes one or more Deferred/Promise objects as arguments.

$.when() returns a master Promise that will resolve when all the individual Promises passed to it have resolved. If any of them reject, the master Promise immediately rejects.

`$.when()` Example: Parallel Fetch

Let's simulate fetching two different data sets in parallel. We'll use $.Deferred() to mimic AJAX requests for demonstration.

Try running this code:

// Assume jQuery is loaded in the environment
$(function() {
  function fetchData(name, delay) {
    let dfd = $.Deferred();
    setTimeout(function() {
      console.log(`Finished fetching ${name}`);
      dfd.resolve(`Data for ${name}`);
    }, delay);
    return dfd.promise();
  }

  let profilePromise = fetchData("User Profile", 1500);
  let settingsPromise = fetchData("App Settings", 800);

  console.log("Starting parallel fetches...");

  $.when(profilePromise, settingsPromise)
    .done(function(profileData, settingsData) {
      console.log("All data loaded successfully!");
      console.log(`Profile: ${profileData}`);
      console.log(`Settings: ${settingsData}`);
    });
});

Handling `$.when()` Results

When the $.when() Promise resolves, its .done() callback receives the resolved values from each of the original Promises as separate arguments.

  • If you pass N Promises to $.when(), the .done() callback will receive N arguments.
  • The arguments are in the same order as the Promises were passed to $.when().

This makes it easy to work with all the results once they are ready.

`$.when()` Error Handling

What happens if one of the parallel operations fails? $.when()'s master Promise will immediately reject if any of the individual Promises reject.

The .fail() callback will then be triggered, receiving the rejection reason from the first Promise that failed. The remaining parallel operations will still complete, but $.when() will have already signaled failure.

Example: `$.when()` with Failure

Let's modify the previous example so one of the fetches fails. Observe the output:

// Assume jQuery is loaded in the environment
$(function() {
  function fetchData(name, delay, shouldSucceed = true) {
    let dfd = $.Deferred();
    setTimeout(function() {
      if (shouldSucceed) {
        console.log(`Finished fetching ${name}`);
        dfd.resolve(`Data for ${name}`);
      } else {
        console.log(`Failed to fetch ${name}`);
        dfd.reject(`Error: ${name} could not be loaded`);
      }
    }, delay);
    return dfd.promise();
  }

  let profilePromise = fetchData("User Profile", 1500, true);
  let settingsPromise = fetchData("App Settings", 800, false); // This one will fail

  console.log("Starting parallel fetches (one will fail)...");

  $.when(profilePromise, settingsPromise)
    .done(function(profileData, settingsData) {
      console.log("All data loaded successfully! (This won't run)");
    })
    .fail(function(errorReason) {
      console.log("One or more operations failed!");
      console.log(`Reason: ${errorReason}`);
    });
});

Coordinating Dependent Tasks

Sometimes, tasks aren't independent. You might need to:

  • Fetch a user ID.
  • Then, use that ID to fetch the user's details.
  • Then, use those details to fetch their specific posts.

This requires a sequential chain of asynchronous operations, where each step depends on the success and result of the previous one. We achieve this by chaining .then() or .pipe().

Example: Chaining Dependent AJAX

Here's how you can chain two simulated AJAX calls where the second depends on the first's result. Notice how the return value of the first .then() becomes the input for the next.

// Assume jQuery is loaded in the environment
$(function() {
  function fetchUserId() {
    let dfd = $.Deferred();
    setTimeout(() => {
      console.log("User ID fetched: 123");
      dfd.resolve(123);
    }, 500);
    return dfd.promise();
  }

  function fetchUserDetails(userId) {
    let dfd = $.Deferred();
    setTimeout(() => {
      if (userId === 123) {
        console.log(`Details fetched for user ${userId}`);
        dfd.resolve(`Details for User ${userId}`);
      } else {
        dfd.reject("Invalid User ID");
      }
    }, 700);
    return dfd.promise();
  }

  console.log("Starting dependent fetch chain...");

  fetchUserId()
    .then(function(id) {
      return fetchUserDetails(id); // Return a new promise
    })
    .done(function(details) {
      console.log("Full chain successful!");
      console.log(`Final Result: ${details}`);
    })
    .fail(function(error) {
      console.log("Chain failed:", error);
    });
});

Test Your Knowledge

Consider a scenario where you want to load a user's profile and their friend list. The friend list request needs the user's ID, which is part of the profile data.

Which jQuery approach is best suited for this specific coordination?

Recap: Mastering Async Coordination

You've learned how to handle multiple asynchronous tasks effectively!

  • $.when(): Ideal for running independent tasks in parallel and waiting for all to complete or any to fail.
  • Chaining with .then(): Perfect for dependent tasks, where one operation's output is needed for the next.
  • Error Handling: Both $.when() and chained Promises provide .fail() to catch rejections at any point, making your applications more robust.

These patterns are crucial for building dynamic and responsive web applications with jQuery.

Frequently asked questions

Is the “Handling Multiple Asynchronous Tasks” lesson free?

Yes — the full text of “Handling Multiple Asynchronous Tasks” is free to read here on the web, and the jQuery Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the jQuery Academy course, upgrade to CoddyKit PRO.

What will I learn in “Handling Multiple Asynchronous Tasks”?

Master the art of coordinating several independent or dependent asynchronous tasks, ensuring proper execution order and error handling across all operations. You practise jQuery Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start jQuery Academy?

No prior experience is required. jQuery Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Handling Multiple Asynchronous Tasks” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this jQuery Academy lesson?

Yes. Every jQuery Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Understanding Deferred Objects
  2. Chaining and Composing Promises
  3. Handling Multiple Asynchronous Tasks
← Back to jQuery Academy