嵌套异步调用似乎未按预期执行

Nested asynchronous calls do not seem to execute as expected

本文关键字:执行 异步 调用 嵌套      更新时间:2023-09-26

在尝试jQuery时,我有一个问题可能是新手的错误,但我似乎找不到解决方案。这是代码:

$.get("index.html", function() {
    var i = 0;
    for (; i < 3; i++)
    {
        var lDiv = document.createElement('div');
        lDiv.id = 'body-' + i;
        document.getElementById('body').appendChild(lDiv);
        $.get('index.html', function(data) {
            lDiv.innerHTML = "<p>Hello World " + i + "</p>";
        });
    }
});

输出似乎是

<div id='body-0'></div>
<div id='body-1'></div>
<div id='body-2'>
    <p>Hello World 3</p>
</div>
我希望为每个 i 执行

lDiv.innerHTML=代码,但显然它只针对最后一个 i 执行?我忽略了什么?

发生这种情况是因为循环在触发任何回调之前完成(i为 2)。

@thecodeparadox的解决方案有效,但它序列化 HTTP 请求。 (使它们一次发射一个。 这允许请求并行执行,因此速度更快:

for (var i = 0; i < 3; i++)
{
    var lDiv = document.createElement('div');
    lDiv.id = 'body-' + i;
    document.getElementById('body').appendChild(lDiv);
    $.get('index.html', function(i,lDiv) { // the current iteration's `i` and `lDiv` are captured...
        return function(data) {
            lDiv.innerHTML = "<p>Hello World " + i + "</p>";
        }
    }(i,lDiv)); // ...by passing them as an argument to the self-executing function
}

由于$.get()是异步的,所以你需要在$.get()success()回调函数中执行追加和下一次调用。

var i = 0;
function recursiveLoad() {
       if(i == 3) return;
       var lDiv = document.createElement('div');
       lDiv.id = 'body-' + i;
       document.getElementById('body').appendChild(lDiv);
       $.get('index.html', function(data) {
            lDiv.innerHTML = "<p>Hello World " + i + "</p>";
            i++;
            recursiveLoad();
       });
}
// initial call
recursiveLoad();