Why are the values ​​in js variables different?

  • 0
    Good evening, I have a question about JavaScript.
    There is the following piece of code.
    function start() {
            update();
            /*let timerId = setInterval(update, 1000);*/
          }
    
          function update() {
            let now = new Date();
            document.getElementById("time").innerHTML = "Время: " + now;
    
            $.ajax(
              'get_users.php', {
                success: function(data1) {
                  var users = JSON.parse(data1);
                  for (key in users) {
                  	$.ajax({
                        url: "https://api.vk.com/method/users.get?user_ids=" + users[key]['vk_id'] + "&fields=photo_50&access_token=token&v=5.124",
                        type: 'GET',
                        dataType: 'jsonp'
                      })
                      .done(function(data2) {
                        console.log("Key:" + key + "\n" + data2.response[0].photo_50);
                      });
                    console.log(key);
                    console.log(users[key]['vk_id'] + "\n" + users[key]['nickname'] + "\n" + users[key]['balanse']);
                    document.getElementById("status" + key).innerHTML = users[key]['nickname'] + " " + users[key]['balanse'];
                    document.getElementById("photo" + key).style.display = "block";
                  }
                },
                error: function() {
                  alert("There was some error performing the AJAX call!");
                }
              }
            );
          }

    But the key value is different when I make ajax request to VK API.
    This is what it outputs to the console.

    And when receiving a user photo, the key is the same, why?
    JavaScript Anonymous, May 29, 2020

  • 1 Answers
  • 0
    Because asynchronous. By the time data arrives in .done, the loop has already finished its work and key is equal to the last value.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!