来自承诺的调用方法
问题描述:
你好,我有包含几个方法的对象。在其中一个中,我使用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
关键字不能按预期工作,那么如何在此时启动另一种方法?还有一个不那么重要的问题 - 这就是我正在做的命名链接?
答
可以存储这样的背景下在,然后用这个新的变量该做操作
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);
};
});
},
溶液1 - 使用箭头函数'。然后((响应)=> {' - 解决方法二,保存对此的引用,例如在'var _this = this;'之外说。然后函数,并使用_this在里面它 –
https://*.com/questions/34930771/why-is-this-undefined-内部使用类的方法当使用承诺 – Donal
知道有一个骗局:p –