1

I'm trying to pass the result from an SQLite SELECT to the var res and show it but in the alert I get "undefined". How to correctly return it?

function read(key){
    app.db.transaction(function(tx) {
        tx.executeSql('SELECT value FROM MyTable WHERE key = ?',
            [key],
            function(tx, results)
            {
                return results.rows.item(0)['value']
            },                
            app.onError
        );
        return;
    });
    return;
}

res=read("pipi")
alert(res);
Joel
  • 4,732
  • 9
  • 39
  • 54
Alex Stanese
  • 735
  • 4
  • 16
  • 33

1 Answers1

2

You cannot return a value from an asynchronous function. You need to either pass a function that will execute with the results of the async function OR use a global variable to hold the results.

res=read("pipi") // will always return undefined

you can declare a global variable and a global function.

resultSelect = "";
function alertResultSelect(result){
    alert(result);
}

then in your function(tx, results) code add

function(tx, results)
{
   //Assign the results to the global variable.
   resultSelect = results.rows.item(0)['value'];
   // OR call the global function
   alertResultSelect(results.rows.item(0)['value']);
}
frank
  • 3,180
  • 3
  • 16
  • 18
  • the gloval variable dont work. the out put is still "" and the option 2 I would like to use the resoult further in my code.. to assign it to a varable and to use it further in the deviceready (where all my code is placed) – Alex Stanese Jul 22 '14 at 17:34