0

I have a problem how to properly call/return one function data. I have this function displayTableWithCountryStates which is calling getCountryStates function. The problem is that when i make request $.get i get proper response, but when i try to return this response, console.log(countryStates) inside displayTableWithCountryStates is empty

countryStatesTables = {

    displayTableWithCountryStates: function (source, newForm) {
        var countryId = 237;
        var countryStates = countryStatesTables.getCountryStates(countryId);
        console.log(countryStates); // Response is empty
    },

    getCountryStates: function (countryId) {
        if (countryId !== '' || countryId !== 'undefined') {
            $.get(balthazar.settings.logistics.getCountryStatesUrl.url + '/' + countryId, function (data) {
                console.log(data.data); //Response is ok, data is present
                return data.data;
            });
        }
    }
};

Why and how to properly return data in my displayTableWithCountryStates function. If you need any additional informations, please let me know and i will provide. Thank you!

Valor_
  • 3,461
  • 9
  • 60
  • 109
  • 2
    Look in the console at the *order* your two console.logs are shown, the empty one is first because the `$.get` is asynchronous - ie hasn't finished yet. See link for more details. – freedomn-m Jul 26 '17 at 12:07
  • may be you should use keyword `this` : var countryStates = this.getCountryStates(countryId); – Bakhtiiar Muzakparov Jul 26 '17 at 12:09

1 Answers1

4

Asynchronous functions need callbacks to handle the data as we don't know exactly when they would return the output. You can also it with promises.

countryStatesTables = {

    displayTableWithCountryStates: function (source, newForm) {
        var countryId = 237;
        var countryStates = this.getCountryStates(countryId, function(data){
          console.log(countryStates);
        });
    },

    getCountryStates: function (countryId, callback) {
        if (countryId !== '' || countryId !== 'undefined') {
            $.get(balthazar.settings.logistics.getCountryStatesUrl.url + '/' + countryId, function (data) {
                console.log(data.data); //Response is ok, data is present
                callback(data.data);
            });
        }
    }
};
Sourab Reddy
  • 353
  • 2
  • 14
  • 1
    We dont' need ***yet another*** answer to this question. – T.J. Crowder Jul 26 '17 at 12:12
  • 1
    I realize that fact perfectly well, but I felt that if the person has asked this question he is a newbie to async function calls and probably to javascript, so I answered anyway. Marking the question as duplicate could be the right thing to do but I understand the place this guy is in so hell with that strict attitude ! – Sourab Reddy Jul 26 '17 at 12:16
  • Exactly! Thank you @SourabReddy – Valor_ Jul 26 '17 at 12:18