I have a function that accepts a callback function where I pass the data back in. Can this converted to a deferred object for better practice?
Here is what I got:
var chapters;
var getChapters = function (fnLoad) {
//CACHE DATA IF APPLICABLE
if (!chapters) {
//CALL JSON DATA VIA AJAX
$.getJSON('/chapters.txt')
.done(function (json) {
//STORE DATA IN LOCAL STORAGE
chapters = Lawnchair(function () {
this.save(json, function (data) {
//CALL CALLBACK ON DATA
fnLoad(data);
});
});
});
} else {
//RETURN ALREADY CREATED LOCAL STORAGE
chapters.all(function (data) {
//CALL CALLBACK ON DATA
fnLoad(data);
});
}
};
Then I simply use it like this:
this.getChapters(function (data) {
console.log(data);
});
How can I use it like a promise though while maintaining the cache approach?
this.getChapters().done(function (data) {
console.log(data);
});
Relevant example
I see you have already accepted an answer, however if you take a large mental leap and store a promise of
chapters
instead of thechapters
themselves, then the code will simplify significantly.These days, this is probably the more generally adopted approach for a "fetch/cache" situation.
What is actually promised (the chapters) will be determined by the value(s) returned by the functions
Lawnchair
andthis.save
, so you still have some work to do.getChapters()
will always return a promise, regardless of whether the data needs to be fetched or is already cached. Therefore,getChapters()
can only be used with promise methods.then()
,.done()
,.fail()
or.always()
, for example :You have no other way to access the
chapters
but that is reasonable since at any call ofgetChapters()
, you don't know whether it will follow the$.getJSON()
branch or the simplereturn
branch, both of which return an identical promise.