NOTE: I am using jQuery version 1.7.2.
I'm trying to understand jQuery promises and deferred objects.
I have the following code:
var that = this;
var dataRetrieved = that.retrieveData();
$.when(dataRetrieved).then(function(data) {
that.formatDataForTemplate(data);
});
retrieveData: function () {
if ( // condition A ) {
return window.data.conditionA;
} else if (// condition B) {
return window.data.conditionB;
} else {
this.fetch({
success: function (status, response) {
return response;
}
});
}
}
basically, I want to pass in whatever data is returned from retrieveData
into the .then()
function, but it doesn't seem to work. the retrieveData()
function is being called (checked with a console.log), however the formatDataForTemplate
is not being called.
retrieveData()
may return data instantly, or may return data from an AJAX query (this.fetch({});
). I need the .then()
to only fire once data has been returned from retrieveData
.
I think I'm just not understanding promises clearly. How can I make my code accomplish what I'm trying to do?
EDIT: hm, still not quite getting the hang of it.. Here's my updated version. I'm trying to figure out how to return a promise that has been resolved with my data.
var that = this;
var dataRetrieved = that.retrieveData();
dataRetrieved.then(function(data) {
that.formatDataForTemplate(data, that.get('template'));
});
retrieveData: function () {
var that = this;
if (window.settings.preview === 'true') {
return $.Deferred(function(def) {
def.resolveWith(window.settings.previewData);
});
}
// else if mock (during dev), use mock data.
else if (this.get('is_mock')) {
var mocked_data = {
"title":"Mock Title",
"description": "Mock Description"
};
// return mocked_data;
return $.Deferred(function(def) {
def.resolveWith(mocked_data);
});
}
// else, hit API like normal.
else {
return $.Deferred(function (def) {
that.fetch({
success: function (status, response) {
def.resolveWith(response);
}
});
});
}
},