-1

Hello I have object which contains few methods. In one of them I am using promise to execute another one and I am using .then to retrieve some data from it.

Within .then my this keyword is changed and I can not figure out how to call again another method from this point.

So the method I'm writing about is:

    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);
            };
        });

    },

inside if() statement I'm doing a simple calculation and then I want to pass the result to addTax() method (in the very same object) but this keyword doesn't work as expected in this case, so how can I start another method at this point? And less important question - is this what I'm doing named chaining?

BT101
  • 2,674
  • 3
  • 26
  • 61
  • 2
    solution 1 - use an arrow function `.then((response) => {` - solution two, save a reference to this, say in `var _this = this;` outside that .then function, and use _this inside it – Jaromanda X Sep 04 '17 at 10:55
  • https://stackoverflow.com/questions/34930771/why-is-this-undefined-inside-class-method-when-using-promises – Donal Sep 04 '17 at 10:56
  • knew there was a dupe :p – Jaromanda X Sep 04 '17 at 10:57
  • Sorry for duplicate I was looking for answer but couldn't find good keywords. Now I know how to accomplish that. Last question - is it chaining? – BT101 Sep 04 '17 at 11:10

1 Answers1

0

you can store the context of this in that, then use this new variable that to do operations

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);
            };
        });

    },
marvel308
  • 9,593
  • 1
  • 16
  • 31