返回executeSQL函数 [英] Return executeSQL function
问题描述
我试图使用SQLite返回SQL查询的结果。
查询工作正常,我可以输出executeSql函数内的结果。但是当我尝试从我的主要函数(returnSQLArray)到达数组,它是未定义的。
我如何解决这个问题?
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?
我在另一个函数中调用returnSQLArray,我需要查询的结果。
I'm calling returnSQLArray inside another function where I need the results from the query.
代码:
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
}
谢谢
推荐答案
这是一个异步问题。 db.transaction
接受在sqlite事务完成后执行的回调。您的方法结束时显示的 console.log()
语句实际上是在填充 result
之前发生的。
It's an async issue. db.transaction
takes a callback which executes after the sqlite transaction finishes. Your console.log()
statement shown at the end of your method is actually happening before result
has been populated.
编辑添加:
functions getPersons() {
returnSQLArray('SELECT * FROM PERSONS', processPersonsResponse);
}
function returnSQLArray(str, callback) {
...
tx.executeSql(str, [], function(tx, rs) { callback(result); });
}
function processPersonsResponse(response) {
//do work with response
}
这篇关于返回executeSQL函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!