简体   繁体   中英

Javascript: How do I get an objects to push in an array in the right order inside a for loop with an ajax request

So I have this script that connects to a video service api and I am trying to push the video titles that are served up in the ajax request in the order of the video_codes array. So these video codes are for seperate videos that give out information such as titles from the api ( 3t7l1ok4ba gets alicia , 5cj3ro2ujq gets drew , etc.)

    // these codes connect to the api and get data
    var video_codes = [
    '3t7l1ok4ba',
    '5cj3ro2ujq',
    'ztodsfeifx',
    'u4g78mwyee'
]

// this is to hold the video titles provided in the api
var names = [];

// for loop makes the different requests
for (i = 0; i < video_codes.length; i++){
    (function(i) {
        var video_request = new XMLHttpRequest()
        video_request.open('GET', 'https://api.wistia.com/v1/medias/'+video_codes[i]+'.json?api_password=', true)
        video_request.onload = function() {
          var video = JSON.parse(this.response)
          var video_name = video.name;

          // add to names array
          names.push(video_name);
          // console log names array 4 times
          console.log(names)
        }
        video_request.send()
    })(i);
}

the script works in the sense that it pushes the names to the name array and console logs but they dont correspond to the order of the video_codes array.

So for example 3t7l1ok4ba pushes out alicia but sometimes alicia will be the second, third, or fourth entry. It is completely random i get different results everytime I run the script. Any help would be greatly appreciated!

The problem is the order the console logs is the order that the api responds. You are making all requests at the same time, so the second request may return before the first. One way to maintain the order is doing the next request only after the previous returned:

function loadVideo(i) {
  if (i < video_codes.length) {
    var video_request = new XMLHttpRequest()
    video_request.open('GET', 'https://api.wistia.com/v1/medias/'+video_codes[i]+'.json?api_password=', true)
    video_request.onload = function() {
      var video = JSON.parse(this.response)
      var video_name = video.name;

      // add to names array
      names.push(video_name);
      // console log names array 4 times
      console.log(names);
      loadVideo(i + 1); // Load next only after response received
    }
    video_request.send()
  }
}

loadVideo(0); // Load first video

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM