I want to create a JS array of 1 or many functions, each with their own parameters (provided within a closure), then invoke of all of those functions, and have a callback for when all are called.
Based on the answer for this question, I can create 1 function with the parameters needed:
var f = (function(value) {
return function(){myFunction(value);};
}(k));
I want to have several of these functions, invoke them all, and provide a callback after all are called.
Here is a JSFiddle that attempts to do this, and does not work the way I want (it never calls my 3 functions).
This JSFiddle, using jQuery.Deferred objects (it calls my 3 functions too soon).
The way I would expect the consle.log() output to be is:
do something first
f1 done variable one
f2 done variable two
f3 done variable three
all functions have completed
callback has been called
What am I missing? How can I solve this issue?
EDIT: There will be an unknown number of functions to be called (set arbitrarily from throughout my application), which is why I am pushing them to an array.
Check the Deferred docs under the constructor section:
That is, the functions run as soon as you pass them to the
Deferredconstructor. So, one possible way to solve the issue is tof1,f2,f3regular functions, which accept thedfdparameter and resolve itDeferredonly when you’re ready to run them.This Fiddle produces your expected output.