function suitable for accessing array values

Asked

Viewed 34 times

0

I have a file with a function that takes all records from a table, as below.

window.lerTabelaListas=function()
    {
       lista=new Array();
        db.transaction(function  (tx)
        {

         tx.executeSql('SELECT * FROM listas',[],function  (tx, results)
         {

             var len= results.rows.length, i;
             for(i=0; i<len; i++)
             {
               var nome=results.rows.item(i).nome
               var id=results.rows.item(i).idLista
            lista.push(nome,id)


             }


         });

    }); 
   return lista;
   }

When I call this function I can’t get any feedback, I can’t, for example, make a foreach to extract these values. By log console, but he returns:

Array(32)
0
:
"lista de: 2/3/2018"
1
:
1
2
:
"lista básica "

I need some help, guys, since I’m a beginner in Javascript.

  • The executeSql works asynchronously, it does not "wait" the result to then return the value.

  • Let me see if I understand, excecute sql works independently,? What/how could I do then,

  • Basically.. What you can do is use one Promise or a function of callback.

  • Thanks, I’ll read about

1 answer

0

Create a global variable outside the function:

var resultado = window.lerTabelaListas;
console.log(resultado);

// A sua função
window.lerTabelaListas=function()
{
   lista=new Array();
    db.transaction(function  (tx)
    {

     tx.executeSql('SELECT * FROM listas',[],function  (tx, results)
     {

         var len= results.rows.length, i;
         for(i=0; i<len; i++)
         {
           var nome=results.rows.item(i).nome
           var id=results.rows.item(i).idLista
        lista.push(nome,id)


         }


     });

}); 
return lista;
}

Browser other questions tagged

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