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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With