2014-05-19 4 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 (또는 창 개체)로 설정되어 있습니다. 그러나 Parse promises를 사용하고 있고 Promises/A + 준수 여부가 확실하지 않으므로 임의의 것들이 될 수 있습니다 - HTTP 요청 또는 기타. 엄격한 코드와 좋은 약속 라이브러리에서는 예외 였을 것입니다.

대신, 대신 this를 사용하는 명시 적으로 CustomObject.cachedValue을 수행 할 수 있습니다

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

감사합니다. 이것이 내가 함께 간 것입니다. 그냥 전에 가까운 팸을 추가해야했습니다. (또한 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 objec t가 아니라 전역 개체입니다.

변경 같은 코드 :

... 
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