Deferred was created to execute the code after answering some remote call (i.e.: ajax).
so you can:
load_conf = function (user_id) { var def = $.Deferred() $("http://get_conf_data_url?user_id="+user_id).done(function (data) { var processed_conf = do_something_with(data); def.resolve(processed_conf); }) return def.promise(); }
so you can go:
load_conf(1).done(function (processed_data) { do_something_with(processed_data); });
How to execute some code after loading exacly 3 configurations? You can do something like:
$.when(load_conf(1), load_conf(2), load_conf(3)).done(function (c1, c2 ,c3) { console.log("configurations: ", c1, c2, c3); })
But what about the execution of some code after loading the N-configurations, where N is a variable? In this case, you can use the Function.prptotype.apply method. You can pass an object to be considered as "this" inside the function as the first argument. The second argument is a list of parameters, but inside the array.
so you can do the following:
var defs = []; for (var i=1; i<=N; i++) { defs.push(load_conf(i)); }
source share