我有一個函數接受一個回調函數,我將數據傳回去了。可以將它轉換爲延期對象以便更好地練習嗎?如何將回調示例轉換爲延期對象?
這裏是我的了:
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);
});
}
};
然後,我只是用這樣的:
this.getChapters(function (data) {
console.log(data);
});
我如何使用它像一個承諾,雖然同時保持高速緩存的方法呢?
this.getChapters().done(function (data) {
console.log(data);
});
jQuery的ajax方法擴展了延遲對象。您已經在使用它... –
但是請注意,我在操縱數據並在傳回數據之前在中間的某處使用「Lawnchair」,因此我無法返回ajax對象? – TruMan1
爲什麼你的評論全部大寫? – Eric