0
let movies = [];

fetch(endPoint)
.then((res) => res.json())
.then((data) =>
{
  // console.log(data);

  data.results.forEach((element) =>
  {
     movies.push(element.id);
  })

console.log(movies);

  for(let i = 0; i < movies.length; i++)
  {
    console.log(movies[i]);
  }


})


console.log(movies);

So I am fetching an API and putting all the id's returned from the results array into my array of movies. How come my array values from movies are being printed differently outside my fetch block?

  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ASDFGerte Dec 08 '19 at 23:02
  • Please do some research next time this has been asked literally dozens of times, thanks – Dexygen Dec 08 '19 at 23:18

2 Answers2

0

When using functions that are asynchronous, results come at different times. With the code above, here is what happens.

Variables initialized

Fetch function is called.
Sends a request to a server. 
Functions are added to fetch function.

Movies is printed.

Request is returned with data.
Fetch function returns object.
.then function is called.
Other .then function is called
Stuff is printed.

When you do the fetch function, it is sent, but because your web browser or computer doesn’t want to freeze, it continues to read and run code, not waiting for the request to finish. Once the request does finish, it is almost certain all your code will have been initialized and run. Happy coding, and welcome to Stack Overflow.

theParadox42
  • 65
  • 1
  • 7
0

You are using thenable promise which is not waiting to finish the execution of api request and moving to execute the next statement. and a note: do not put your private data like api key and all on public platform. BTW below is solution to your problem:

async function getData(){
  const endPoint = "https://api.themoviedb.org/3/movie/now_playing?api_key=334b0e3c899b3e21c9b8157d672aee02&language=en-US&page=1";

  let response = await fetch(endPoint);
  let data = response.json();
  let movies = data.results.map(movie => movie.id);
  console.log(movies);
}
Ajay Kumar
  • 99
  • 6