I have this function that seems to be doing what it should:
var getData = function(query)
{
var data = [];
db.transaction(function(tx) {
tx.executeSql(query, [], function (tx, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
data.push(results.rows.item(i));
}
}, error);
});
return data;
}
When I do a console.log(data), it shows an array of objects with correct data, as you can see in an example from Chrome’s console:

However, data.length is 0, making it impossible to iterate. I’ve tried
for(var i = 0; i < data.length; i++) {
$('.regions').append(data[i].region + '<br>');
};
which is no good since data.length is 0. I’ve tried
for(var key in data) {
$('.regions').append(data[key].region + '<br>');
};
which doesn’t work, presumably for the same reason. I even tried $.each() from jQuery, but nothing even enters the loop. I do a console.log(data) right before these loops to double check it still has the data as I would expect. I manually recreated the data by hand with
data = [
{
available: "1",
company_id: 1,
cultivar: "Cultivar 2.0",
cultivar_id: 18,
id: 18,
image: "b0c2dd4765422fc0acce9461a040ebaf.png",
logo: "980f2a610d681ade5b5b42511f89655c.png",
maintenance: "Fairway",
maintenance_id: 7,
name: "Cultivar 2.0",
region: "Midwest",
region_id: 24,
species: "Perennial Ryegrass",
species_id: 7,
trait_disease: "Disease 2",
trait_disease_id: 6,
available: "1"
},
{
company_id: 1,
cultivar: "Cultivar 2.0",
cultivar_id: 18,
id: 18,
image: "b0c2dd4765422fc0acce9461a040ebaf.png",
logo: "980f2a610d681ade5b5b42511f89655c.png",
maintenance: "Fairway",
maintenance_id: 7,
name: "Cultivar 2.0",
region: "Midwest",
region_id: 24,
species: "Perennial Ryegrass",
species_id: 7,
trait_disease: "Disease 2",
trait_disease_id: 6
}
];
and that type of thing appeared exactly the same in the console, but it worked when I iterated over it. I have done a few other things I found around StackOverflow, including making sure that it indeed was recognized as an array.
Even if I knew the length, data[0] is undefined. I have spent some sweet time on this and wondered if anything else had any ideas.
This has been tested in Chrome 18.0.1025.151 (Firefox doesn’t have sqlite) and it will eventually go onto a phone with jQuery Mobile and PhoneGap, but we’re not at that point, yet. Just a simple HTML page with a sqlite database.
Thanks!
Your fundamental problem is that you’re expecting to be able to return the result of an asynchronous operation from the function that initiates it.
The call to “.executeSql()” returns immediately. At some point after that, the database operation completes and your callback function is invoked. However, the containing function (“getData()”) has long since returned.
The way to make an API around asynchronous operations is to make your own API asynchronous. Give “getData()” another parameter so that its clients can pass in a handler function. Then, from the callback, invoke the handler and pass it the array as a parameter.