angularjs - 在 Angular 应用程序中缓存 parse.com Promise 的结果

标签 angularjs parse-platform promise

我希望我的对象缓存某些网络请求的结果并回答缓存的值,而不是执行新请求。 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/

相关文章:

Java/解析错误。试图从 android sdk 发送到 Parse

swift - 如何使用 Swift 在 TableViewController 中包含不是主查询表的 Parse 类的计数?

node.js - 如何将对象或变量与 Promise.all 一起传递?

javascript - 电话间隙 :Angularjs find in Json Array

iOS swift,从 JSON 数组中检索和删除特定对象 Parse.com

mysql - 如何在 NodeJS 中的相同代码中返回 promise 并关闭 mysql 连接

node.js - 破坏 promise 链 - 停止执行下一个 'then'

html - 如何将多个div居中并向左浮动?

angularjs - 如何设置 angularjs select 来处理对象

javascript - 在 AngularJS 中使用嵌套 Controller 时,$scope 对象是否在所有 Controller 之间共享