Call ASYNC - AJAX

Asked

Viewed 118 times

2

I have a problem with calls in AJAX, I need to make more than one call in AJAX to store in different variables and in that I can treat them.

I’m just having trouble with AJAX’s ASYNC, because it’s taking too long to load the information from the Apis I call.

I’ve tried everything until I put one AJAX call inside another, but that’s not correct and it didn’t work because when leaving the second Success of the second call the value of the variable is lost.

Could someone help me how to do this otherwise?

My code below:

<script type="text/javascript">
            var vUsers;
            var vAlbums;
            var length;


            $(document).ready(function() {
                $.ajax({ url: 'https://jsonplaceholder.typicode.com/users',
                    async: true,
                    success: function(data1) {
                        vUsers = data1;                                
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        alert(thrownError);

                        return false; 
                    }
                });



                $.ajax({url: 'https://jsonplaceholder.typicode.com/photos',
                    async: true,
                    success: function(data2) {
                        vAlbums = data2;            
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        alert(thrownError);

                        return false; 
                    }
                });



                var table = document.getElementById('table');

                function contaAlbums(lineId) {
                    length = 0;

                    vAlbums.forEach(function(album) {
                        if (album.userId == lineId) { alert(lineId + '   ' + album.userId);
                            length++;
                        }
                    });

                    return length;
                };


                vUsers.forEach((line) => {
                    var lineId   = line.id;
                    var tr       = document.createElement('tr');
                    var username = document.createElement('td');
                    var name = document.createElement('td');    
                    var email = document.createElement('td');    
                    var city = document.createElement('td');
                    var tdAlbums = document.createElement('td');

                    alert(lineId);

                    var albumCount = contaAlbums(lineId);

                    username.innerText = line.username;
                    name.innerText = line.name;
                    email.innerText = line.email;
                    city.innerText = line.address.city;
                    tdAlbums.innerText = albumCount;

                    tr.append(username, name, email, city, tdAlbums);
                    table.append(tr);
                });     
            }); 
        </script>

I need to pick up various information to be able to present in a table as image below: inserir a descrição da imagem aqui

  • 2

    you are trying to use the value of vUsers to make a foreach before waiting for the async call to return. It would be interesting to move this to a Function and call that Function on success from the first ajax, just after setting the variable vUsers

  • 2

    the second problem is that in the code we use the vUsers, tbm needs the value of vAlbuns, which is another name of another async call, that is, you need this code to be executed when you return both calls. For this you can use the $.when(, which receives a list of files (would have to put both ajax calls in a Function) or use tbm Promise.all( who has the same idea, which includes an answer below

1 answer

4


You can use the Promise concept to do this. You can read more about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

For your specific case change your ajax request to

Promise.all([
   $.ajax({
      url: 'https://jsonplaceholder.typicode.com/users',
      async: true,
   }),
   $.ajax({
      url: 'https://jsonplaceholder.typicode.com/photos',
      async: true,
   })
]).then(([vUsers, vAlbums]) => {
   // Coloque o código que edita sua tabela aqui
});

Promise will await the return of the two asynchronous requests and then execute whatever is between the then

  • Thank you Mauricio, it worked perfectly, thank you.

Browser other questions tagged

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