I'm trying to return the results of a SQL query using SQLite. The query works fine and I can output the results inside the executeSql function. But when I try to reach the array from my main function (returnSQLArray) it is undefined. How do I solve this problem?
I'm calling returnSQLArray inside another function where I need the results from the query.
Code:
function returnSQLArray(str)
{
var db = window.openDatabase("Database", "1.0", "Name", 200000);
var result = [];
db.transaction(
function (tx, results) {
tx.executeSql(str, [], function(tx, rs) {
for(var i=0; i<rs.rows.length; i++) {
var row = rs.rows.item(i)
result[i] = {
id: row['id']
}
}
console.log(result[0].id); //Returns the id
});
}
);
console.log(result[0].id); //Undefined
}
Thank you
It's an async issue.
db.transaction
takes a callback which executes after the sqlite transaction finishes. Yourconsole.log()
statement shown at the end of your method is actually happening beforeresult
has been populated.EDIT ADDITION: