Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web SQL SELECT transaction return value

I am trying to call a function that SELECTS values from my Web SQL database. I would like to return the SELECTED values into a variable inside the parent function. But, the variable always returns blank, wether it is global or not.

As you will be able to see the console.log inside the selectRow function logs the correct values from the the database query, but the console.log shows up blank in the initDB function.

I have also noticed that the blank log shows up before the log inside the selectRow function. I have found forums where people are talking about database transactions being asynchronous. I understand that this is why my variable being returned is blank. However, after beating my head against the wall many times I still can't find a way to work around this asynchronous issue.

/** Initialize Database  **/
function initDB(){
  createTable();
  var pleaseWork = selectRow("SELECT * FROM planets;");
  console.log(pleaseWork);
}

/** Select Row from Table **/
function selectRow(query){  
  var result = [];

  db.transaction(function (tx) {
    tx.executeSql(query, [], function(tx, rs){  
      for(var i=0; i<rs.rows.length; i++) {
        var row = rs.rows.item(i)
        result[i] = {
          id: row['id'],
          name: row['name']
        }
      } 
      console.log(result);
    }, errorHandler);
  });  

  return result;
}
like image 974
Tyler Buchea Avatar asked Oct 19 '11 04:10

Tyler Buchea


1 Answers

You could change your selectRow() function to accept a callback as a parameter, which it will call with the result rather than returning the result:

/** Initialize Database  **/
function initDB(){ 
   createTable();
   selectRow("SELECT * FROM planets;", function(pleaseWork) {
     console.log(pleaseWork);
     // any further processing here
   });
}  

/** Select Row from Table **/ 
function selectRow(query, callBack){ // <-- extra param
   var result = [];
   db.transaction(function (tx) {
      tx.executeSql(query, [], function(tx, rs){
         for(var i=0; i<rs.rows.length; i++) {
            var row = rs.rows.item(i)
            result[i] = { id: row['id'],
                          name: row['name']
            }
         }
         console.log(result);
         callBack(result); // <-- new bit here
      }, errorHandler);
   });
} 
like image 103
nnnnnn Avatar answered Oct 05 '22 08:10

nnnnnn