Angularjs angular app中parse.com承诺的缓存结果

Angularjs angular app中parse.com承诺的缓存结果,angularjs,parse-platform,promise,Angularjs,Parse Platform,Promise,我希望我的对象缓存一些网络请求的结果,并回答缓存的值,而不是执行新的请求。使用angular Promission完成看起来很像我想要的,但是我不确定如何使用Parse.com Promission库来表达它。这是我正在尝试的 module.factory('CustomObject', function() { var CustomObject = Parse.Object.extend("CustomObject", { cachedValue: null,

我希望我的对象缓存一些网络请求的结果,并回答缓存的值,而不是执行新的请求。使用angular Promission完成看起来很像我想要的,但是我不确定如何使用Parse.com Promission库来表达它。这是我正在尝试的

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;
             });
         },

我的想法是返回一个承诺,不管值是否被缓存。在缓存该值的情况下,该承诺将立即得到解决。问题是,当我在调试器中执行此操作时,我似乎无法在第二次调用时获得缓存结果。

您可以缓存承诺并返回它

module.factory('CustomObject', function() {

  var CustomObject = Parse.Object.extend("CustomObject", {

    cachedPromise: null,

    getValue: function() {
        if (!this.cachedPromise) {
            this.cachedPromise = this.functionReturningPromise();
        }
        return this.cachedPromise;
    },
  ...
  }
  ...
}
您的值几乎是正确的。您的设计是正确的。这里唯一的问题是动态

.then
处理程序的上下文中,
这个
被设置为未定义(或窗口对象),但是-因为您使用的是解析承诺,我不确定这些承诺是/A+兼容的,所以它可以是任意的东西-HTTP请求,或者其他什么。在严格的代码和良好的promise库中,这将是一个例外

相反,您可以显式地执行
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
承诺也可以代替解析承诺,我会使用它们:

var cachedValue = null;
getValue: function() {
    return $q.when(cachedValue || this.functionReturningPromise()).then(function(theValue){
         return cachedValue = theValue;
    });
}

我不熟悉Parse.com promise库,但这可能是一个简单的JS错误:
函数中的
this
不是指承诺对象,而是指全局对象

更改代码如下:

...
getValue: function() {
    if (this.cachedValue) return Parse.Promise.as(this.cachedValue);

    var that = this;
    return this.functionReturningPromise().then(function (theValue) {
        that.cachedValue = theValue;
        return that.cachedValue;
    });
},

为什么不缓存原始承诺并返回它呢?我也不知道Parse.Object在本地JavaScript上给了您什么。@BenjaminGruenbaum我不完全确定,但他们的示例代码就是这样做的。它至少可以实现save()和destroy()之类的功能。事实上,如果parse.com承诺是承诺/A+投诉,那么它将引用全局错误,我不确定它们是否是-例如,这个假设与jQuery promissions.Ah相违背。我看到了(还有这个)。谢谢,谢谢。这就是我要的。只需要在之前添加一个关闭参数。然后。(另外,我发现Parse.Promise有一个when方法)。