2014-05-19 36 views
2

我想我的對象緩存一些網絡請求的結果,並回答緩存的值,而不是做一個新的請求。 This answer here完成使用角度承諾看起來很像我要去的,但我不知道如何使用Parse.com諾言庫來表達它。這是我想要...緩存結果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; 
      }); 
     }, 

我的想法是返回一個承諾,無論該值是否緩存。在緩存該值的情況下,該承諾立即解決。問題是,正如我在調試器中所看到的,我似乎沒有在第二次調用時獲得緩存結果。

+0

你爲什麼不只是緩存當初的諾言,並返回? – JoseM

+0

我也沒有看到Parse.Object通過本機JavaScript在這裏提供了什麼。 –

+0

@BenjaminGruenbaum我不完全確定,但他們的示例代碼是這樣做的。至少有一件事情是實現諸如save()和destroy()之類的東西。 – someShmuck

回答

1

你的價值幾乎正確。你的設計是正確的,你在這裏唯一的問題是動態的this

.then處理程序的情況下,this設置爲undefined(或窗口對象),但 - 因爲你使用解析的承諾,我不知道那些承諾/ A +標準的也可以是任意的東西 - HTTP請求,或其他。在嚴格的代碼和一個良好的承諾庫 - 這將是一個例外。

相反,你可以做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; 
    }); 
} 
+0

謝謝。這是我一起去的。只需要添加一個關閉paren之前。然後。 (另外,我發現Parse.Promise有一個when方法)。 – someShmuck

1

你可以只緩存的承諾並返回

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

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

    cachedPromise: null, 

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

謝謝。緩存承諾是一個好主意! – someShmuck

1

我不熟悉Parse.com諾言庫,但它可能是一個普通的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; 
    }); 
}, 
+0

事實上,如果parse.com承諾是Promises/A +投訴,我不確定它們是否是 - 例如,這個假設違反了jQuery承諾,它會引用全局錯誤。 –

+0

啊。我看到(和這個)。謝謝。 – someShmuck