Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
53
rated 0 times [  55] [ 2]  / answers: 1 / hits: 40149  / 13 Years ago, wed, october 19, 2011, 12:00:00

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;
}

More From » sql

 Answers
135

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);
});
}

[#89542] Monday, October 17, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hasancolec

Total Points: 603
Total Questions: 95
Total Answers: 98

Location: South Korea
Member since Sat, Oct 2, 2021
3 Years ago
;