How are $.when, apply(), and $.done() interacting in this function?

ajax, javascript, jquery, jquery-deferred

Solution

`$.when` returns a new promise, so `$.when().done()` just calls `.done` on the promise returned by `$.when`.

`.apply` lets you call a function with arguments in an array instead of passing them individually. So

$.when.apply(null, dfdArr)

is (nearly*) equivalent to

$.when(dfdArr[0], dfdArr[1], dfdArr[2], ...);

Each of the elements in `dfdArr` is a promise.

*except for the value of `this` inside the function.

Problem

A while ago, a SO user wrote this function for me to return a variable number of jQuery `$.get()` requests. The first part is pretty straightforward, but will someone elplain how `$.when()`, `apply()`, and `$.done()` are interacting. I don't understand in general, but very specifically how they they are accessing the deferred object that `$.get()` returns. ``` function getHTML(qty_of_gets) { var dfdArr = [], i = 1; while (i <= qty_of_gets) { dfdArr.push($.get("get_test_" + i + ".php")); i++; } $.when.apply(null, dfdArr).done(function () { for (var i = 0; i < arguments.length; i++) { $("#content").append(arguments[i][0]); } }); } ```

Original source