我利用jQuery promises来缓存AJAX请求,当我尝试在then子句中返回缓存的promise时,这种方法似乎会中断;我不确定为什么会这样,并想知道是否有办法解决它。
如果我伪造密钥并将if (self.fGetSearchResults.oCache[...
块放在then
块之外的缓存定义下,则代码按预期工作。
MCG.searchControls.fGetSearchResults = function fGetSearchResults() {
var self = this;
var oDeferred = $$.Deferred(); // `new` keyword is optional and we don't like it
var oPromise = oDeferred.promise();
self.fGetSearchResults.oCache = self.fGetSearchResults.oCache || {}; // creates a persistent cache across function calls
// perform the search
$$.when(
self.fPromiseOfFilterObject()
).done(
function fDoneCallback(oFilterObject) {
/* create the RecordListService parameters which we will query with */
..
var oRecordListServiceParametersAsKey = JSON.stringify(oRecordListServiceParameters);
// leverage our cache here
if (self.fGetSearchResults.oCache[oRecordListServiceParametersAsKey] !== undefined) {
return self.fGetSearchResults.oCache[oRecordListServiceParametersAsKey];
} else {
self.fGetSearchResults.oCache[oRecordListServiceParametersAsKey] = oPromise; // cache the result for next time
}
// do the ajax call now
$.orchestracmsRestProxy.doAjaxServiceRequest('ocms_socfp.RecordListService', oRecordListServiceParameters,
function(status, json) {
...
oDeferred.resolve(json)
});
});
return oPromise; // return a our promise object which will resolve at some point
}