Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web SQL transaction does not execute properly in javascript function

I have JavaScript function that returns array of selected values from my local database.

var dataBase = {
  select : selectFunction
}

var db = openDatabase(..);

var data=[ ];
function selectFunction() {
    db.transaction(function (t) {
     t.executeSql("SELECT * FROM Table", [], function (t, results) {
       for (i = 0; i < results.rows.length; i++) {
            data.push(results.rows.item(i));
        }
     });
   });
  return data;//return "stackoverflow" //works fine
}

I want to do something like this

var getSelect = dataBase.select();
alert(getSelect);

If I return string like "stackoverflow", this will work fine

 alert result: stackoverflow

But if I try to return the 'data', the function returns undefined

I noticed that db.transaction is executing after the return statement, and I don't know how to fix this.

like image 439
ToTa Avatar asked Oct 02 '22 07:10

ToTa


1 Answers

When returning results from an asynchronous function, you must use a callback, as the function will return before the actual operation has completed. You can rewrite your function like so:

function selectFunction(callback) {
    db.transaction(function (t) {
     t.executeSql("SELECT * FROM Table", [], function (t, results) {
       for (i = 0; i < results.rows.length; i++) {
            data.push(results.rows.item(i));
        }
        callback(data);
     });
   });
}

And then call it, passing a callback:

dataBase.select(function(data){
    var getSelect = data
    alert(getSelect);
});
like image 119
levi Avatar answered Oct 11 '22 00:10

levi