Return query WebSQL as Array for a global variable

-1

I am using a WebSQL database to save a usage license information in a PhoneGap application. At all times of the system I will need to access this information, so I intend to save this in a global variable in the form of an array. This license to use, when opening the program I perform a function to fetch the information in the WebSQL of the same, but I am not able to insert the return of the function within that global variable. Here's the code:

<!-- language: lang-js -->


//license
LIC = [];

//WebSQL Connect
conn = openDatabase('test', 'test', 'test', 200 * 1024 * 1024);

//return license
function(){

    conn.transaction(function (tx) {

        //sql
        tx.executeSql('SELECT * FROM license', [], function (tx, results) {

            var len = results.rows.length, i;
            //create array response

            for (i = 0; i < len; i++){

                //insert values on response
                LIC['cpfCnpj']     = results.rows.item(i).cpfCnpj;
                LIC['serial']      = results.rows.item(i).serial;
                LIC['apiHash']     = results.rows.item(i).apiHash;
                LIC['status']      = results.rows.item(i).status;

            };

            console.log(LIC); //aqui LIC retorna

        }, null);

        console.log(LIC); //aqui não retorna

    });

}

console.log(LIC); //aqui não retorna

Does anyone have a light there to help me?

    
asked by anonymous 11.11.2014 / 17:26

1 answer

0
Because the executeSql method is asynchronous, and you have to use a Callback , which will only be executed when everything referring to it is "OK", the program ends up executing the bottom lines, and for that reason there is 2 console.log(LIC); that are empty, because they are executed before Callback is executed, and only what is inside Callback is filled. What you can do basically is to call another function at the end of Callback to continue with what you want to do without having any more complications.


Tip:

As in your case it is a query that can be considerably large, it is good practice to show something on the screen while doing the query, some kind of progress bar.     
11.11.2014 / 17:56