How to receive ajax data in a vector?

Asked

Viewed 69 times

0

Hello guys I’m trying to do this, but unsuccessfully:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <section id="lista-filmes"></section>
</body>
</html>

Jquery:

var filmes = [];
$.get("https://www.mocky.io/v2/5ad631b32e00001000c93a96", function(data){
    data.forEach(function(filme){
        filmes.push(filme);
    });
});

$.get(`http://www.omdbapi.com/?i=tt0108037&apikey=???`,function(data){

});
console.log(filmes[0]);

The values I receive are undefined

the idea is, when I consequent accumulate in an array the request, I pass to the second url

for(etc.) {
    $.get(`http://www.omdbapi.com/?i=${filmes[i]}&apikey=???`,function(data)  
    });
}

do something like, to be able to consume the second api.

  • You can’t because the first request is asynchronous.

  • how do I reverse this? what should I study?

1 answer

2


You have to make your for within the callback of the first requisition, because it is asynchronous:

var filmes = [];
$.get("https://www.mocky.io/v2/5ad631b32e00001000c93a96", function(data){
    data.forEach(function(filme){
        filmes.push(filme);
    });

   for(var item of filmes){
      $.get(`http://www.omdbapi.com/?i=${filmes[item]}&apikey=???`,function(data) {
      });
   }
});

But making requests in a loop like this I think is not a good one, but it will depend on what you are wanting to do.

But you can enjoy the first loop forEach instead of doing two:

var filmes = [];
$.get("https://www.mocky.io/v2/5ad631b32e00001000c93a96", function(data){
    data.forEach(function(filme){
        filmes.push(filme);
        $.get(`http://www.omdbapi.com/?i=${filme}&apikey=???`,function(data) {
        });
    });

});
  • 1

    Why two loops? It would not be simpler to make the second direct request in the loop of the first one instead of creating an array that will be traversed next

  • You’re right... I thought about it too, but I didn’t want to optimize... but I will propose

  • the second way it worked, but why did it work? , I tried to do synchronous and it didn’t work either :

  • 1

    worked because the first $get already returned the data... you will be able to synchronise with $.ajax. See in this answer: https://answall.com/a/232516/8063

  • I understood more or less the reason of all, I will give a more thorough study, so I tried with $.ajax with async false, and n rolled, probably was doing something wrong also by not knowing much, but I will give a studied here , thanks for the explanations

  • Thanks. If you need help we’re there.

Show 1 more comment

Browser other questions tagged

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