How to call an ajax function in a for loop [duplic

2020-06-05 06:03发布

I'm new to ajax and JavaScript. What am trying to do is to call an ajax function several times to fetch certain data from a resource and then "push" all of the data into an array so that I can use it later on in the code. Here is my code.

var arr = [];
var users = ["brunofin", "comster404", "ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];

for (i = 0; i < users.length; i++) {
    $.ajax({
        url: "https://api.twitch.tv/kraken/streams/" + users[i],
        success: function(data) {
            arr.push(data);
        },
        error: function(data) {
            arr.push("blank");
        },
        complete: function() {
            if (i == users.length) {
                console.log(arr); //This seem to print even when the condition isn't true
            }
        }
    });
}

The problem with the code is that, it prints to the console even when i isn't equal to users.length

My question is; how do I make certain that it waits until i == users.length is true before it prints to the console? Please keep in mind that I still desire the process to be asynchronous.

7条回答
ら.Afraid
2楼-- · 2020-06-05 06:36

Use a closure indise the loop and bound it with i

var arr = [];
var users = ["brunofin", "comster404", "ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];

for (i = 0; i < users.length; i++) {
(function(x){
 $.ajax({
    url: "https://api.twitch.tv/kraken/streams/" + users[x],
    success: function(data) {
      arr.push(data);
    },
    error: function(data) {
      arr.push("blank");
    },
    complete: function() {
      if (i == users.length) {
        console.log(arr); //This seem to print even when the condition isn't true
      }
    }
  });
})(i)
}
查看更多
登录 后发表回答