1

I am new to js and I am trying to make a loop that gathers movie titles from an api using jquery requests, and save the data in an array called arr like this:

  var arr = []

    var query = inp.value;
    var url = `https://api.themoviedb.org/3/search/movie?api_key=${key}&query=${query}`
    $.getJSON(url, function(data) {
      var data = data.results;
      for (var i = 0; i < 10; i++) {
        var title = data[i].original_title;
        arr.push(title)
      }
    });

  console.log(arr);
  console.log(arr.length);

The problem is when I try to print the new arr length is gives me a length of 0, why is this happening and how do I fix it? enter image description here

JaniniRami
  • 493
  • 3
  • 11
  • 1
    You need to put the console inside the callback when the data is resolved. This is a classic async issue. – Phix Apr 02 '21 at 19:55
  • both console.logs are being executed before callback is resolved, so in that point length array is 0. – Hmorv Apr 02 '21 at 20:02
  • Duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086/4642212). – Sebastian Simon Apr 02 '21 at 20:24

1 Answers1

3

The problem is that when you call $.getJSON it doesn't complete instantly. Your code below (outside of your $.getJSON callback) executes before the call has finished. Here is an example of what is happening.

const arr = [];
$.getJSON('https://jsonplaceholder.typicode.com/todos/1', (json) => {
  arr.push(json);
  console.log('First Log', arr.length);
});
console.log('Second Log', arr.length);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

To get the correct arr.length to log, you need to place them within your callback.

Example:

var arr = []

var query = inp.value;
var url = `https://api.themoviedb.org/3/search/movie?api_key=${key}&query=${query}`
$.getJSON(url, function(data) {
  var data = data.results;
  for (var i = 0; i < 10; i++) {
    var title = data[i].original_title;
    arr.push(title)
  }
  console.log(arr);
  console.log(arr.length);
});

What isn't mentioned here is what you are trying to ultimately do. I would assume that you have the arr defined as a global variable for a reason. You may want to change your callback so that your code calls whatever subsequent thing that does something with the data returned from the API once the call is complete.

mwilson
  • 12,295
  • 7
  • 55
  • 95