What does $.when.apply($, someArray) do?

.apply is used to call a function with an array of arguments. It takes each element in the array, and uses each as a parameter to the function. .apply can also change the context (this) inside a function.

So, let’s take $.when. It’s used to say “when all these promises are resolved… do something”. It takes an infinite (variable) number of parameters.

In your case, you have an array of promises; you don’t know how many parameters you’re passing to $.when. Passing the array itself to $.when wouldn’t work, because it expects its parameters to be promises, not an array.

That’s where .apply comes in. It takes the array, and calls $.when with each element as a parameter (and makes sure the this is set to jQuery/$), so then it all works 🙂

Leave a Comment