I'm confused about how to use jQuery's Deferred object, and the examples I've seen aren't helping me. What I want to do is 1.) get a calendar object via an ajax call, 2.) populate part of my global object (MYOBJ) with the calendar data, and then 3.) populate a page element with the new data in MYOBJ. These three functions implement the logic, and I want to call them in sequence:
function getCalendar(refDate, numDays) {
return $.ajax({
type: "POST",
url: "services/Calendar.asmx/GetCalendar",
data: '{ "refDate": "' + refDate + '", "numDays": "' + numDays + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json"
}).promise();
}
function loadCalendarData(response) {
var calData = jQuery.parseJSON(response.d);
MYOBJ.cal.dMin = calData.dMin;
MYOBJ.cal.dMax = calData.dMax;
MYOBJ.cal.dates = calData.dates; // array of date strings
}
function populateCalendar (x, y, z) {
// use data from MYOBJ.cal here
}
I can't figure out how to make populateCalendar() wait until loadCalendarData() is done, though. This...
$.when(getCalendar(myDate, 70))
.then(loadCalendarData)
.then(populateCalendar(a, b, c))
.fail(alertCalendarError);
...is obviously incorrect--it's just one variation I've thrown against the wall because I don't understand what I'm doing... :)
UPDATE: As GoldenNewby and Brian ONeil correctly point out, I could just stick my call to populateCalendar at the end of loadCalendarData. That will definitely work. I wish I had thought of that as I was posting. I guess my ultimate objective was to figure out how to achieve the sequencing. In this case, though, I can't think of any scenario where loadCalendarData would be called without a call to populateCalendar directly after it, so this solution definitely makes sense. Thanks.