我希望我的对象缓存某些网络请求的结果并回答缓存的值,而不是执行新请求。 This answer here使用 Angular Promise 完成的看起来很像我想要的,但我不确定如何使用 Parse.com Promise 库来表达它。这就是我正在尝试的...
module.factory('CustomObject', function() {
var CustomObject = Parse.Object.extend("CustomObject", {
cachedValue: null,
getValue: function() {
if (this.cachedValue) return Parse.Promise.as(this.cachedValue);
return this.functionReturningPromise().then(function (theValue) {
this.cachedValue = theValue;
return this.cachedValue;
});
},
我的想法是返回一个 promise ,无论该值是否被缓存。在缓存该值的情况下,该 promise 将立即得到解决。问题是,当我在调试器中遵循此操作时,我似乎没有在第二次调用时获得缓存的结果。
最佳答案
您的值几乎正确。您的设计是正确的,您遇到的唯一问题是动态this
。
在 .then
处理程序的上下文中,this
设置为未定义(或窗口对象),但是 - 因为您正在使用 Parse Promise 并且我'我不确定这些是否符合 Promises/A+,它可以是任意的东西 - HTTP 请求,或其他什么。在严格的代码和良好的 promise 库中 - 这将是一个异常(exception)。
相反,您可以显式执行 CustomObject.cachedValue
而不是使用 this
:
var CustomObject = Parse.Object.extend("CustomObject", {
cachedValue: null,
getValue: function() {
if (CustomObject.cachedValue) return Parse.Promise.as(this.cachedValue);
return this.functionReturningPromise().then(function (theValue) {
CustomObject.cachedValue = theValue;
return this.cachedValue;
});
},
如果 $q
promise 也可以代替 Parse promise ,我会使用它们:
var cachedValue = null;
getValue: function() {
return $q.when(cachedValue || this.functionReturningPromise()).then(function(theValue){
return cachedValue = theValue;
});
}
关于angularjs - 在 Angular 应用程序中缓存 parse.com Promise 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23746830/