【问题标题】:Cache result of parse.com promise in angular app在角度应用程序中缓存 parse.com 承诺的结果
【发布时间】:2014-05-19 20:40:51
【问题描述】:

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

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

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

【问题讨论】:

  • 你为什么不缓存原始的承诺并返回呢?
  • 我也看不到 Parse.Object 在本机 JavaScript 上为您提供了什么。
  • @BenjaminGruenbaum 我不完全确定,但他们的示例代码就是这样做的。它至少做的一件事是实现了 save() 和 destroy() 之类的东西。

标签: angularjs parse-platform promise


【解决方案1】:

您的值几乎正确。您的设计是正确的,您在这里遇到的唯一问题是动态 this

.then 处理程序的上下文中,this 设置为未定义(或窗口对象),但是 - 因为您使用 Parse 承诺,我不确定它们是否符合 Promises/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 承诺也可以代替 Parse 承诺,我会使用它们来代替:

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

【讨论】:

  • 谢谢。这就是我一起去的。只需要在 .then 之前添加一个关闭括号。 (另外,我发现 Parse.Promise 有一个 when 方法)。
【解决方案2】:

你可以只缓存承诺并返回

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

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

    cachedPromise: null,

    getValue: function() {
        if (!this.cachedPromise) {
            this.cachedPromise = this.functionReturningPromise();
        }
        return this.cachedPromise;
    },
  ...
  }
  ...
}

【讨论】:

    【解决方案3】:

    我不熟悉 Parse.com 的 promise 库,但它可能是一个普通的 JS 错误:
    函数内部的this不是指Promise对象,而是指全局对象。

    像这样更改代码:

    ...
    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.com 承诺是 Promises/A+ 投诉,​​它会指全局错误,我不确定它们是否 - 例如,这个假设与 jQuery 承诺不符。
    • 啊。我看到了(和这个)。谢谢。
    猜你喜欢
    • 2020-07-13
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 2016-02-10
    • 2013-12-07
    相关资源
    最近更新 更多