Javascript值分配延迟?

Ale*_*lex 0 javascript jquery

我现在不知所措.我正在使用一个简单的变量,其值在循环期间分配.退出循环后,变量的值仍未定义,除非我首先提醒它的值.一切正常.这里发生了什么?

$(myarray).each(function(idx, item)
{
     fetchSomethingRemotely( success: function(data) {
           item.someValue = data; });

     // if the following alert is not there, doSomething will never get called
     // and the alert after the else will show item.someValue as undefined.
     alert(item.someValue);

     if (item.someValue != null) { doSomething(item.someValue); }
     else { alert(item.someValue); }

});
Run Code Online (Sandbox Code Playgroud)

编辑:

好的,所以我现在有了更好的处理方式.值赋值(item.someValue = 123)发生在此迭代中的回调函数内部.所以当我连续尝试访问下面几行代码时,该值可能还没有.我怎么能等待分配值?

cas*_*nca 5

我怎么能等待分配值?

答案已在您的代码中.只需doSomething进入回调函数即可.

fetchSomethingRemotely( { success: function(data) {
       item.someValue = data;
       if (item.someValue != null) doSomething(item.someValue);
} });
Run Code Online (Sandbox Code Playgroud)

请注意,在当前项目获得其值之前,这仍将继续到下一个项目.如果必须按顺序执行所有迭代,则可以执行以下操作:

function iterate(index) {
  var item = myarray[index];
  fetchSomethingRemotely( { success: function(data) {
    item.someValue = data;
    if (item.someValue != null) doSomething(item.someValue);
    if (index < myarray.length - 1) iterate(index + 1);
  } });
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以开始整个过程​​了iterate(0).