Why do I get a different array?

2020-05-09 11:49发布

Good day. I have problem with give different arrays;

my code next:

setInterval(function() {

var TestName = [];
var requests = [];
TestName.push('0');
for($i=1; $i<8; $i++) {
    var id = $i;
    requests.push($.post("./Scripts/", {
    record:id,
    opt:'get_test'
    }, function(data){
          TestName.push(data);
    }));
}

 $.when.apply($,requests).done(function(){

     for($i=1; $i<8; $i++) {
$('#test'+$i).html('').html(TestName[$i]);

}
alert(TestName);
 });

}, 15000);

This code works but every time I get different arrays...

For example:

alert(TestName); result one:

0,
<a href="#"><img src="./images/test1.png"></a>,
<a href="#"><img src="./images/test2.png"></a>,
<a href="#"><img src="./images/test3.png"></a>,
<a href="#"><img src="./images/test4.png"></a>,
<a href="#"><img src="./images/test5.png"></a>,
<a href="TestTestTestTestTest.php"><img src="./1358997710.jpg"></a>,
<a href="#"><img src="./images/test7.png"></a>,

alert(TestName); result two:

0,
<a href="#"><img src="./images/test1.png"></a>,
<a href="#"><img src="./images/test2.png"></a>,
<a href="TestTestTestTestTest.php"><img src="./1358997710.jpg"></a>,
<a href="#"><img src="./images/test3.png"></a>,
<a href="#"><img src="./images/test5.png"></a>,
<a href="#"><img src="./images/test4.png"></a>,
<a href="#"><img src="./images/test7.png"></a>

As you can see elements of the array each time exchange seats, and sometimes elements of the array are arranged in the wrong order.

Tell me please where may be been error in code?

1条回答
狗以群分
2楼-- · 2020-05-09 12:46

The reason your array is different each time is that you are running asynchronous requests and then populating from the callback. Each time you do this your requests happen to be finishing in different order and therefore populating the array in a different order.

You must not rely on async request callbacks being called at any particular point within your execution, they can be called at any time, depending on when the response decides to come back.

查看更多
登录 后发表回答