Reputation: 3484
Here is a very easy one I guess (but JS is not my best friend and I'm stuck...)
How can I return the rows
value ? (which is undefined...)
function myFunction(table){
html5sql.process(
["SELECT * FROM "+table],
function(transaction, results, rowsArray){
rows = rowsArray; // rows is defined here
},
function(error, statement){
});
return rows; // rows is not defined here :(
}
Upvotes: 0
Views: 174
Reputation: 86575
You're probably not going to be able to do that as you have things now. With JS being by default asynchronous, rows
will be returned even before any of those callbacks run. Since the success callback is what sets rows
, you'll always be returning an either unset or stale value.
(Note: i have never used html5sql. It might be that the library just presents an interface that looks async while somehow actually working synchronously. But if it does, it'd be quite unusual in that regard.)
One possible fix would be to take a callback yourself, that you call and pass the rows to once you get them.
function myFunction(callback){
html5sql.process(
["SELECT * FROM "+table],
function(transaction, results, rowsArray){
callback(rowsArray);
},
function(error, statement){
});
}
// and use it like this
myFunction(function(rows) {
// do stuff with rows in here
});
Or, just use callback
as the second arg to process
, if you want to be lazy. Just know that it will be passing all three args, which the caller of this function shouldn't have to care about. :P
Upvotes: 4
Reputation: 4972
minor change...
function myFunction(){
var rows;
html5sql.process(
["SELECT * FROM "+table],
function(transaction, results, rowsArray){
rows = rowsArray;
},
function(error, statement){
});
return rows;
}
You're getting an undefined because you havent really defined it it - doing so at the beginning of the function will make it specific to that scope and should return properly.
Upvotes: 0
Reputation: 125660
Declare rows
before assigning it's value:
function myFunction(){
var rows;
html5sql.process(
["SELECT * FROM "+table],
function(transaction, results, rowsArray){
rows = rowsArray; // rows is defined here
},
function(error, statement){
});
return rows; // rows is not defined here :(
}
That changes the variable scope, and makes it visible and accessible outside inner function as well.
Upvotes: 0