I'm trying to use a function to initialize datas with 3 ajax calls, and when this function is done I want to do something with the datas. I have to wait for the 3 ajax calls to be done before I can return a promise. The thing is, if I wait for the 3 ajax calls to be done (with $.when (ajax1, ajax2, ajax3).done(...)), I get the error "Cannot read property 'then' of undefined"
Here is my code
function myInit() {
initData().then(function() {
console.log("a");
});
}
function initData() {
var results = {
categories: [],
commandes: [],
users: []
};
var ajaxCategories = $.ajax({
url: url + '/categorie/getAll',
success: function(data) {
results.categories = data;
}
});
var ajaxCommandes = $.ajax({
url: url + '/statistique/getSimpleCommandes',
success: function(data) {
results.commandes = data;
}
});
var ajaxUsers = $.ajax({
url: url + '/statistique/getSimpleUsers',
success: function(data) {
results.users = data;
}
});
$.when(ajaxUsers, ajaxCommandes, ajaxCategories)
.done(function() {
results.commandes.forEach(function(commande) {
results.users.forEach(function(user) {
if (user.id == commande.user)
commande.user = user.nom;
});
});
return $.Deferred().resolve();
});
}
I return a promise in the $.when. If I move this return outside of the when, it works fine, but then I risk getting out of the function and continuing my code with the datas not loaded. Where is my mistake?