Search code examples
javascriptthischaining

Calling method from promise


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?


Solution

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