I have a function to get some data, and the function should return a promise. In the function, I have to made 2 requests - one after another. I ended up with a nested deferrer call where the last call resolves
on the deferrer the function will return. I'm new to this deferred stuff and wonder if this is the right solution.
function getData(func) {
var model = new Model();
var collection = new Collection();
var dfd = new jQuery.Deferred();
collection.fetch().then(function () {
model.fetch().then(function () {
dfd.resolve(collection);
});
});
return dfd.then(function (collection) {
return getViews(func(collection), model);
});
}
If the order of the calls does not matter I would suggest to use http://api.jquery.com/jQuery.when
With
when
you can make parallel xhr requests.Andreas, I see you have quite correctly accepted Vitaliy's answer and I'm not trying to steal his points but just in case you are not aware, there's no need to create and resolve your own
$.Deferred()
and there's no need to passcollection
around (except tofunc()
) as it remains in scope.As far as I can tell from the code in the question, the following should work :