0

I have a backbone.js project. I use jquery$get function inside. I am changing the value of the variable defined above in get. But when I do console.log (cityValue) outside, I see the old value.Can you help me? I look forward to your ideas.

Sample code;

getFormattedAddress1: function () {            
        var postalCodeValue = this.model.get(this.postalCodeField);
        var streetValue = this.model.get(this.streetField);
        var cityValue = this.model.get(this.cityField);
        var stateValue = this.model.get(this.stateField);
        var countryValue = this.model.get(this.countryField);            

        $.get("Target/action/city", { id : cityValue },function(data){
            cityValue = data.name;
        });

        console.log(cityValue);

        var html = '';
        if (streetValue) {
            html += streetValue;
        }
        if (cityValue || stateValue || postalCodeValue) {
            if (html != '') {
                html += '\n';
            }
            if (cityValue) {
                html += cityValue;
            }
            if (stateValue) {
                if (cityValue) {
                    html += ', ';
                }
                html += stateValue;
            }
            if (postalCodeValue) {
                if (cityValue || stateValue) {
                    html += ' ';
                }
                html += postalCodeValue;
            }
        }
        if (countryValue) {
            if (html != '') {
                html += '\n';
            }
            html += countryValue;
        }
        return html;
    },
Gündoğdu Yakıcı
  • 677
  • 2
  • 10
  • 31
  • `$.get()` is asynchronous. you are logging the variable in console even before the get request completes. Try executing the code that depends on `cityValue` in `$.get().done()`. [Docs here](https://api.jquery.com/jquery.get/#jqxhr-object) – Fr0zenFyr Mar 22 '18 at 12:10
  • But you see. In my code they are all in one function only. – Gündoğdu Yakıcı Mar 22 '18 at 12:59
  • 2
    Doesn't matter that it is all inside one function (and technically you have two functions: `getFormattedAddress1` and the `$.get` callback). `$.get` is asynchronous so its callback won't be executed until after the code after `$.get` has already executed. You have to turn it inside-out and use callbacks. – mu is too short Mar 22 '18 at 17:49

1 Answers1

1

jQuery's get is performing an asynchronous request - meaning that the callback function(data) { ... } will be executed after the network request to Target/action/city finishes. The rest of the code not inside the callback will execute without waiting for the network request to finish.

So basically, console.log(cityValue); runs before cityValue = data.name; hence you're seeing the old value.

Try putting the console.log(cityValue); inside the callback function.

Dhruv Murarka
  • 376
  • 5
  • 12