2017-09-04 1 views
-1

안녕하세요 저는 방법이 거의없는 객체를 가지고 있습니다. 그들 중 하나에서 나는 다른 것을 실행하기 위해 약속을 사용하고 있으며 어떤 데이터를 가져 오기 위해 .then을 사용하고 있습니다.약속으로부터의 호출 방법

.thenthis 키워드가 변경되어이 지점에서 다른 방법을 다시 호출하는 방법을 알 수 없습니다.

그래서 나는 대해 쓰고 있어요 방법은 다음과 같습니다 나는 간단한 계산을하고 있어요 다음 내가 (매우 동일한 객체) addTax() 방법에 결과를 전달하려는하지만

convertToUSD: function(selectedCurrency,priceField) { 
     var priceField = priceField; 
     var selectedCurrency = selectedCurrency; 

     console.log('selectedCurrency in service: '+selectedCurrency); 
     console.log('priceField in service: '+priceField); 

     var currentCurrency = this.getRatio(selectedCurrency); 
     currentCurrency.then(function(response) { 
      console.log(response); 
      console.log('to USD: '+response.toUSD); 
      if(response.toUSD !== undefined){ 
       var userPriceInUSD = priceField*response.toUSD; 
       console.log(userPriceInUSD); 
       this.addTax(userPriceInUSD); 
      }; 
     }); 

    }, 

if() 내부 이 경우에 this 키워드가 예상대로 작동하지 않으므로이 시점에서 다른 방법을 시작하려면 어떻게해야합니까? 덜 중요한 질문입니다. 제가 연쇄 체인이라는 것입니까?

+2

액 (1)을 수행하기 위해 새로운 변수 를 사용할 수있다 - 그 때는 화살표 함수 '((대응) =>를 사용 {'- 해결책 2, 이것에 대한 참조를 저장하고, 그 안에 함수를 사용하고 내부에 이것을 사용하는 'var _this = this;'라고 말하십시오. –

+0

https://stackoverflow.com/questions/34930771/why-is-this-undefined- 내부 클래스 방법 - 언제 - 사용 약속 - – Donal

+0

은 속는 사람이 있다는 것을 알고 있었다 : p –

답변

0

는 다음, 즉이 컨텍스트 저장 동작

convertToUSD: function(selectedCurrency,priceField) { 
     var priceField = priceField; 
     var selectedCurrency = selectedCurrency; 

     console.log('selectedCurrency in service: '+selectedCurrency); 
     console.log('priceField in service: '+priceField); 
     var that = this; // this stores the context of this in that 
     var currentCurrency = this.getRatio(selectedCurrency); 
     currentCurrency.then(function(response) { 
      console.log(response); 
      console.log('to USD: '+response.toUSD); 
      if(response.toUSD !== undefined){ 
       var userPriceInUSD = priceField*response.toUSD; 
       console.log(userPriceInUSD); 
       that.addTax(userPriceInUSD); 
      }; 
     }); 

    },