Array has values, but its length is zero

Asked

Viewed 197 times

1

I need to iterate on this array, however, although it is not empty the length of it returns 0 as you can see, someone knows the reason?

inserir a descrição da imagem aqui

The scenario is as follows: I am receiving JSON data from an API and iterating over the objects to place the property values I want in this single array. I have to iterate on it now, but with size 0 broke the logic.

//apkikey
//base_url
var tags = [];
var keywordsId = [];


function tagsData(){
  var input_tags =  $('.chips').material_chip('data');

  input_tags.forEach(function(tag){
    tags.push(tag.tag);
  });
}

function findKeyWordId() {

  tags.forEach(function(tag){
    var url = base_url + 'search/keyword' + '?api_key=' + apikey + '&query=' + tag + '&page=1';

    $.getJSON(url, function(response){
      response.results.forEach(function(tag_obj){
        keywordsId.push(tag_obj.id);
      });
    });

  });

  console.log(keywordsId);
};

function searchMovies() {
tagsData();
findKeyWordId();

  console.log("Tamanho do array: " +  keywordsId.length);

    keywordsId.map(function(id){
    var movie_url = base_url + 'keyword/' + id  + '/movies' + '?api_key=' + apikey;

    $.getJSON(movie_url, function(results){
      console.log(results);
    });

  });
}
  • 2

    You can show the code that generates that console.?

  • exceeded the space here, but is available in jsfiddle: link

  • That one base_url is public? if yes what is the value?

1 answer

0

I found out what was giving me a headache, it wasn’t anything magical, but the fact that Javascript was asynchronous, I was calling my functions callback at the wrong time so I had a wrong perception of what was happening.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.