简体   繁体   中英

Returning variables inside JS / JSON functions

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM