问题
I have a page that has to display information from a websql database. However the page loads with blanks, even though the information is in the database. I am guessing that the page gets populated before the database is open / active? Is there anything I can do so slow the page load or speed up the database load?
回答1:
I was struggling with the same issue. Below is the sample db service function code.
Reason this was happening because web-sql calls are asynchronous. For example, below getItemData is returning itemData before mapItemRow converts the resultset into required object type.
getItemData:function(){
var itemData= [];
_dbCon.transaction(function (tx) {
var queryExp = 'SELECT description as Item, amount as Amount from inventory';
tx.executeSql(queryExp, [],mapItemRow);
}, dbConnectionFactory.errorDBSql, dbConnectionFactory.successDBSql);
function mapItemRow(tx, results) {
console.log('Calling mapItemRow....')
var len = results.rows.length;
for (i = 0; i < len; i++) {
itemData.push({ITEM: results.rows.item(i).description, Amount: results.rows.item(i).amount});
}
return itemData;
};
}
I am also using angularJs so to fix this problem i used $q and promise functionality. Let me know if you are interested to see the solution.
In your case you can use settimeout functionality:
var millisecondsToWait = 500;
setTimeout(function() {
// call your db service
}, millisecondsToWait);
You can also implement solution like waitfor mentioned in following link: Wait until a condition is true?
You can also think of using some other db libraries which can handle these asynch calls like jaydata or breeze.
Hope this helps you.
来源:https://stackoverflow.com/questions/21402597/page-before-database-phonegap