views:

38

answers:

1

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)
});
A: 

I guess StackOverflow.getSomething() runs an AJAX request? So what is defined inside of it's callback (looping through a and b) is not executed until the AJAX request is finished. What happens is that StackOverflow.getSomething is fired and then console.log(result) at the end of your code is executed immediately afterwards. By that time, the callback of StackOverflow.getSomething hasn't been run yet, and result hasn't been updated yet. Only "Sample stuff" is logged. But when the second console.log is executed in the callback after the AJAX request (of getSomething), result is updated and logged "correctly".

In other words, the execution order would be this

  1. Set result to "Sample stuff"
  2. StackOverflow.getSomething() fires an AJAX request with an attached callback function
  3. console.log(result) logs "Sample stuff"
  4. The ajax callback finishes and fires its callback function. result is updated accordingly by iterating over a and b
  5. The callback function's console.log(result) logs the final value of result
Simen Echholt
Thanks for the explanation. I think I may have assumed most of that, but still don't know how to go about having the "result" from getSomething() tie into getJSON() so that it happens before the rest of getJSON() is executed.
Mike B.
If you depend on `result` to be correct for the rest of getJSON to function properly, you'll have to put the rest of the getJSON code into the callback of `StackOverflow.getSomething` :)
Simen Echholt