for循环内ajax调用的行为 [英] behavior of ajax call inside a for loop

查看:632
本文介绍了for循环内ajax调用的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  for (var i in arr) {
    console.log(i);
    $.get(searchURL, function (result) {
      console.log(result);
    }); // end of inner async request
  } // end of outer arr

在这种情况下,我看到了

In this case, I am seeing

1
2
3
result
result
result

但是我的意图和期望是

1
result
2
result
3 
result

我认为发生这种情况是因为每个ajax调用花费的时间都比整个for循环的执行时间长.这是正确的吗?如果是这样,传统的做法是什么?

I assume this happens because each ajax call is taking longer than the entire for loop's execution. Is this right? If so, what is the conventional way of doing this?

更新:

我发现使用jQuery的$.each函数而不是for loop给了我预期的输出. $.each函数是否旨在与循环内的异步调用一起使用?

I found using jQuery's $.each function instead of for loop gives me the expected output. Is $.each function intended to work with async calls inside loops?

推荐答案

它启动所有三个异步ajax调用,然后一个接一个地调用,结果从它们中返回.由于它们是异步的,因此直到当前的javascript线程完成并返回事件队列以开始提供到达的ajax结果之前,都不会处理任何结果.您看到的结果仅与以下事实有关:ajax调用是异步的,并且与返回结果所需的时间无关.

It launches all three asynchronous ajax calls and then one by one, the results come back from them. Because they are asynchronous, no results will be processed until the current thread of javascript finishes and gets back to the event queue to start serving the arriving ajax results. The results you see has only to do with the fact that the ajax calls are asynchronous and nothing to do with how long they take to come back with the results.

如果要串行运行它们,则可以构造代码以调用ajax调用,然后在结束时调用下一个ajax调用,依此类推:

If you want to run them serially, then you structure your code to call on ajax call and then, when that finishes, call the next ajax call and so on like this:

function doAjax(arr) {
    var i = 0;

    function next() {
        if (i < arr.length) {
            console.log(i);
            // do something with arr[i] here
            $.get(searchURL, function (result) {
                 console.log(result);
                 i++;
                 next();
            }); // end of inner async request
        }
    }
    next();
}

这篇关于for循环内ajax调用的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆