简体   繁体   English

在JS / JSON函数中返回变量

[英]Returning variables inside JS / JSON functions

I'm trying to understand JSON, callbacks, etc within JS. 我试图了解JS中的JSON,回调等。 From the altered example below, you'll see that I'm in a function callback from $.getJSON. 在下面的示例中,您将看到我在$ .getJSON的函数回调中。 Then, I jump into getSomething() and expect it to alter my result variable. 然后,我进入getSomething()并期望它改变我的结果变量。 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. 您将从2 console.log()看到第一个显示正确,而第二个显示不正确。 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? 我猜StackOverflow.getSomething()运行一个AJAX请求吗? So what is defined inside of it's callback (looping through a and b ) is not executed until the AJAX request is finished. 因此,在AJAX请求完成之前,不会执行其回调(通过ab循环)中定义的内容。 What happens is that StackOverflow.getSomething is fired and then console.log(result) at the end of your code is executed immediately afterwards. 发生的情况是,将触发StackOverflow.getSomething ,然后在代码末尾立即执行console.log(result) By that time, the callback of StackOverflow.getSomething hasn't been run yet, and result hasn't been updated yet. 到那时,尚未运行StackOverflow.getSomething的回调,并且尚未更新result 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". 但是,当第二个console.log在( getSomething )AJAX请求之后在回调中执行时, result被更新并“正确”记录。

In other words, the execution order would be this 换句话说,执行顺序是这样

  1. Set result to "Sample stuff" result设置为“样本内容”
  2. StackOverflow.getSomething() fires an AJAX request with an attached callback function StackOverflow.getSomething()使用附加的回调函数触发AJAX请求
  3. console.log(result) logs "Sample stuff" console.log(result)记录“样本内容”
  4. The ajax callback finishes and fires its callback function. Ajax回调完成并触发其回调函数。 result is updated accordingly by iterating over a and b 通过遍历ab相应地更新result
  5. The callback function's console.log(result) logs the final value of result 回调函数的console.log(result)记录的终值result

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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