0

How can I used the local variable b outside of that function, I tried this but it didn't seem to work, the variable b is still undefined.

$.getJSON("/Home/GetA", function (result) {
    $.each(result, function () {
        if(this.id == '1'){

        }

        else{
            var a = "string 1";
            var b;

                $.getJSON("/Home/GetFeatures", { id: this.id }, function (result) {
                    $.each(result, function () {
                        var b ="moo";
                    });
                });
        var c = a + b;
        }
    });
});
  • 2
    Remove the `var` declaration inside of the `getJSON` callback. – BenM Feb 14 '17 at 19:05
  • tried that, and then I put `alert(b);` outside of the `getJSON` callback and it returns undefined –  Feb 14 '17 at 19:10
  • http://stackoverflow.com/questions/1470488/what-is-the-purpose-of-the-var-keyword-and-when-to-use-it-or-omit-it – Dan Feb 14 '17 at 19:11
  • @DynamicallyLinear You have a race condition. When you alert `b` outside of the block, the callback won't have been triggered. Remember the first "A" in AJAX? That means **asynchronous**. – BenM Feb 14 '17 at 19:13
  • ok thanks Ben, I think it will work fine if I put it outside the `.$each` statement yet still when the ajax callback –  Feb 14 '17 at 19:21

0 Answers0