Reputation: 517
I have several functions where I'm filling a dropdown based on a list from an ajax call :
function getMissions(defaultId) {
$.getJSON("Defaults/GetMissions", function (result) {
var dropDownToFill = $('#change-mission');
fillUpdateDropDown(dropDownToFill, result);
});
}
function getSectors(defaultId) {
$.getJSON("Defaults/GetSectors", function (result) {
var dropDownToFill = $('#change-sector');
fillUpdateDropDown(dropDownToFill, result);
});
}
Now, after dropdown have been filled, I want to select a specific item, but to get this item, I need an other ajax like :
function getDefaultDetails(defaultId) {
$.ajax({
type: "GET",
url: "/Defaults/GetDefault",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { defaultId: defaultId },
success: function (response) {
//code here to select the items from the response
},
});
}
and the main function would basically be :
function main(defaultId){
getMissions(defaultId);
getSectors(defaultId);
getDefaultDetails(defaultId);
}
The trouble is that the success
callback of getDefaultDetails
is reached before fillUpdateDropDown
has been finished (dropdowns could have a lot of items).
I'm trying to understand the callbacks but in my case i cannot achieve my problem. I have tried something like :
$.when(getMissions(defaultId), getSectors(defaultId)).done(getDefaultDetails(defaultId));
but without success.
How to perform that?
Thanks.
Upvotes: 0
Views: 28
Reputation: 21911
$.when()
expects thenable objects (Promise, Deferred, Thenable) like the return value of $.getJSON()
.
You also have to wrap the call for getDefaultDetails()
in .done()
in an anonymous function, otherwise you're executing the function and only use its return value (undefined
) for .done()
function getMissions(defaultId) {
return $.getJSON("Defaults/GetMissions", function (result) {
var dropDownToFill = $('#change-mission');
fillUpdateDropDown(dropDownToFill, result);
});
}
function getSectors(defaultId) {
return $.getJSON("Defaults/GetSectors", function (result) {
var dropDownToFill = $('#change-sector');
fillUpdateDropDown(dropDownToFill, result);
});
}
function getDefaultDetails() { /* ... */ }
$.when(getMissions(defaultId), getSectors(defaultId))
.done(function() { getDefaultDetails(defaultId) });
Upvotes: 1