Reputation: 4552
In the following code, I am retrieving data using $.getJSON
(returned form the repository) and $.when
as the last call is dependent on data from the first:
var getData =
function () {
var data = { userData: null, userTitles: null, userPage: null };
$.when(repository.getUserDetails().done(f1)),
repository.getUserPolicyTitles().done(f2)
.then(repository.getUserPage().done(f3));
function f1(userData) { data.userData = userData; console.log(data.userData) };
function f2(userTitles) { data.userTitles = userTitles; console.log(data.userTitles) };
function f3(userPage) { data.userPage = userPage; console.log(data.userPage) };
return data;
}
return {
getData: getData
};
Most of this works fine. However, I would like to return the data back to a calling module but it returns before the data is ready as I suppose you would expect.
What is the best way to achieve this?
Thanks
Davy
Upvotes: 1
Views: 959
Reputation: 9891
Your usage of deferred seems incorrect. This is my interpretation.
Also, you need to consider that once you start invoking asynchronous methods, you can't make a synchronous return call, which is what you're doing. Instead of returning data, you need to return a promise; then you provide the promise with a callback that will do stuff with the data
var getData = function () {
var myDeferred = $.Deferred();
var data = { userData: null, userTitles: null, userPage: null };
$.when(repository.getUserDetails().done(f1),
repository.getUserPolicyTitles().done(f2),
repository.getUserPage().done(f3)).then(
function(){ myDeferred.resolve(data); },
function(){ myDeferred.reject.apply(myDeferred, arguments); });
//... f1, f2, f3
return myDeferred.promise();
}
return {
getData: getData
};
Then, when you want to actually use the data, you do
your_library.getData().then(function(data){
// magic goes here
}, function(errors_of_some_sort) {
// error handling magic goes here
});
Upvotes: 2
Reputation: 1630
When using $.when, you can only get the data after all your AJAX calls have returned. So for example:
$.when($.getJSON('somewhere'), $.getJSON('somewhere2'))
.done(function(r1, r2){
//set your data object with the responses from the server here
});
So the short answer is you can't "return" the data you retrieved from the server, but you can assign a callback to use the data (or set to some entity of your module) when the data is ready.
Upvotes: 0