0

After retrieve a list of arrays of $fb->get('/me/accounts') in facebook SDK I use this function to retrieve and print de value of accounts.

function recuperarCordeis(){
    var contas = [];
    $.get( "/configuracao/listar_contas", function( data ) {

        for (i = 0; i < data.length; i++) {
                if(Array.isArray(data[i])){
                    obj =data[i];
                    for (x = 0; x < obj.length; x++) {
                        contas.push(obj[x]);
                    }
                }else{
                    console.log('não');
                }

          }
      });

     var html = "";

            for(y = 0; y < contas.length; y++){
            conta = contas[y];
            console.log(conta.provedor_id);
            html += `<div class="img-contas mb-1 ativo">
                <a href="#" class="link-contas">
                    <img src="`+ conta.imagem_avatar +`" class="avatar-contas rounded-circle" />
                    <img src="/images/`+ conta.provedor +`_`+ conta.tipo +`.png" class="img-contas" />
                </a>
                <span>`+conta.nome +`</span>
            </div>
            `;
            }

            alert(html);
            $("#cordeis").html(html);
}

But the code of second for the lenght of contas variable is empty. But its console.log shows an array of objects.

  • 1
    Possible duplicate of [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) – MinusFour Aug 22 '19 at 18:12

1 Answers1

0

JS is asynchronous, meaning that while $.get(...) is fetching data, the code below it gets executed. So. you can use async and await here to wait until the data is actually fetched.

async function recuperarCordeis(){
    var contas = [];
    await $.get( "/configuracao/listar_contas", function( data ) {

        for (i = 0; i < data.length; i++) {
                if(Array.isArray(data[i])){
                    obj =data[i];
                    for (x = 0; x < obj.length; x++) {
                        contas.push(obj[x]);
                    }
                }else{
                    console.log('não');
                }

          }
      });

     var html = "";

            for(y = 0; y < contas.length; y++){
            conta = contas[y];
            console.log(conta.provedor_id);
            html += `<div class="img-contas mb-1 ativo">
                <a href="#" class="link-contas">
                    <img src="`+ conta.imagem_avatar +`" class="avatar-contas rounded-circle" />
                    <img src="/images/`+ conta.provedor +`_`+ conta.tipo +`.png" class="img-contas" />
                </a>
                <span>`+conta.nome +`</span>
            </div>
            `;
            }

            alert(html);
            $("#cordeis").html(html);
}