Hello,
I'm trying to understand JSON, callbacks, etc within JS. From the altered example below, you'll see that I'm in a function callback from $.getJSON. Then, I jump into getSomething() and expect it to alter my result variable. It alters it within the scope of the function, but not when I jump out of that function.
You'll see from the 2 console.log()'s that the first one displays correct, and the second one doesn't. I'm sure the answer to my question has to do with returning variables via. callback, but could someone enlighten
me :)
Thanks!
CODE:
$.getJSON('/cart.js', function (cart, textStatus) {
var result = '';
result += 'Sample Stuff';
StackOverflow.getSomething(param1, param2, function(a, b) {
for(j=0; j < b.length; j++) {
if (b.options[j] != 'Default Title') {
if (a.options[j].name.indexOf("Color") > -1) {
result += b.options[j].name;
console.log(result); // <-- It comes out correct (Sample Stuff + b.options...)
}
}
}
});
console.log(result); // <-- It comes out incorrect, just (Sample Stuff)
});