[英]Returning value from one method to second in callback within object
I have big object which basically is responsible for whole converting money. 我有一个大对象,基本上负责整个兑换货币。
Within this object I've got 4 methods. 在这个对象中,我有4种方法。
addTaxAndShowBack()
is my " main " method and it executes others as a chain with some kind of callback hell. addTaxAndShowBack()
是我的“ main”方法,它以某种回调地狱的形式执行其他程序。
addTaxAndShowBack: function(priceField,selectedCurrency) {
var that = this;
var convertedToUSD = this.convertToUSD(priceField,selectedCurrency)
.then(function(response) {
console.log(response);
var priceInUSD = response;
that.addTax(priceInUSD,selectedCurrency)
.then(function (response) {
console.log(response); // !!! THIS CONSOLE.LOG DOESN'T LOG ANYTHING
}, function () {
console.log('error');
});
}, function (response) {
console.log(response);
});
},
First executed method ( convertedToUSD()
) is working fine it returns converted money from user default currency to USD. 第一个执行的方法(
convertedToUSD()
)工作正常,它将转换后的货币从用户默认货币返回给USD。 Second one is addTax()
and it doesn't return value how I would like to. 第二个是
addTax()
,它不返回我想要的值。 The console.log(response)
doesn't log anything. console.log(response)
不记录任何内容。 The code of addTax
method is: addTax
方法的代码为:
addTax: function(priceInUSD, selectedCurrency) {
var finalPriceInUSD;
if(priceInUSD<300){
// i should also store userPriceInUSD in some variable
// maybe rootScope to send it to backend
finalPriceInUSD = priceInUSD*1.05;
console.log('after tax 5%: '+finalPriceInUSD);
return finalPriceInUSD;
} else {
finalPriceInUSD = priceInUSD*1.03;
console.log('after tax 3%: '+finalPriceInUSD);
return finalPriceInUSD;
}
},
I'm probably doing something wrong in addTax()
not returning correctly or not assigning it correctly in addTaxAndShowBack()
I don't know and that's why I need your help. 我可能在做一些错误
addTax()
没有返回正确或不正确地分配给它addTaxAndShowBack()
我不知道,这就是为什么我需要你的帮助。
return finalPriceInUSD;
this is what response
in addTaxAndShowBack()
in second callback should be. 这是第二个回调中
addTaxAndShowBack()
中的response
。
You are not returning a promise. 您没有兑现承诺。 Try this
尝试这个
addTax: function(priceInUSD, selectedCurrency) {
var finalPriceInUSD;
if(priceInUSD<300){
// i should also store userPriceInUSD in some variable
// maybe rootScope to send it to backend
finalPriceInUSD = priceInUSD*1.05;
console.log('after tax 5%: '+finalPriceInUSD);
return new Promise(res => { res(finalPriceInUSD) });
} else {
finalPriceInUSD = priceInUSD*1.03;
console.log('after tax 3%: '+finalPriceInUSD);
return new Promise(res => { res(finalPriceInUSD) });
}
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.