2017-09-04 93 views
-1

你好,我有包含幾個方法的對象。在其中一箇中,我使用promise來執行另一個,我使用.then從中檢索一些數據。來自承諾的調用方法

.then以內我的this關鍵字已更改,我無法弄清楚如何從這一點再次調用另一個方法。

所以我寫的方法是:

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()聲明我做一個簡單的計算,然後我想將結果傳遞給addTax()方法(在相同的對象),但在這種情況下,this關鍵字不能按預期工作,那麼如何在此時啓動另一種方法?還有一個不那麼重要的問題 - 這就是我正在做的命名鏈接?

+2

溶液1 - 使用箭頭函數'。然後((響應)=> {' - 解決方法二,保存對此的引用,例如在'var _this = 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); 
      }; 
     }); 

    },