How to receive ajax data in a vector?

0

Hello everyone, I'm trying to do this, but without success:

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 proceed to accumulate in a vector the requisition, I move to the second url

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

Do something like this, so you can consume the second api.

    
asked by anonymous 22.04.2018 / 04:25

1 answer

2

You have to make your for within the callback of the first request 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 doing loop requests so I do not think it's a good one, but it will depend on what you're trying to do.

But you can take advantage of the first forEach loop instead of making 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) {
        });
    });

});
    
22.04.2018 / 04:56