Web SQL SELECT 事务返回值
我正在尝试调用一个从我的 Web SQL 数据库中选择值的函数。我想将所选值返回到父函数内的变量中。但是,该变量始终返回空白,无论它是否是全局的。
正如您将能够看到 selectRow 函数内的 console.log 记录了数据库查询中的正确值,但 console.log 在 initDB 函数中显示为空白。
我还注意到空白日志显示在 selectRow 函数内的日志之前。我发现有人在讨论异步数据库事务的论坛。我知道这就是为什么我返回的变量是空白的。然而,在多次将头撞在墙上之后,我仍然找不到解决这个异步问题的方法。
/** Initialize Database **/
function initDB(){
createTable();
var pleaseWork = selectRow("SELECT * FROM planets;");
console.log(pleaseWork);
}
/** Select Row from Table **/
function selectRow(query){
var result = [];
db.transaction(function (tx) {
tx.executeSql(query, [], function(tx, rs){
for(var i=0; i<rs.rows.length; i++) {
var row = rs.rows.item(i)
result[i] = {
id: row['id'],
name: row['name']
}
}
console.log(result);
}, errorHandler);
});
return result;
}
I am trying to call a function that SELECTS values from my Web SQL database. I would like to return the SELECTED values into a variable inside the parent function. But, the variable always returns blank, wether it is global or not.
As you will be able to see the console.log inside the selectRow function logs the correct values from the the database query, but the console.log shows up blank in the initDB function.
I have also noticed that the blank log shows up before the log inside the selectRow function. I have found forums where people are talking about database transactions being asynchronous. I understand that this is why my variable being returned is blank. However, after beating my head against the wall many times I still can't find a way to work around this asynchronous issue.
/** Initialize Database **/
function initDB(){
createTable();
var pleaseWork = selectRow("SELECT * FROM planets;");
console.log(pleaseWork);
}
/** Select Row from Table **/
function selectRow(query){
var result = [];
db.transaction(function (tx) {
tx.executeSql(query, [], function(tx, rs){
for(var i=0; i<rs.rows.length; i++) {
var row = rs.rows.item(i)
result[i] = {
id: row['id'],
name: row['name']
}
}
console.log(result);
}, errorHandler);
});
return result;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以更改
selectRow()
函数以接受回调作为参数,它将使用结果调用该回调,而不是返回结果:You could change your
selectRow()
function to accept a callback as a parameter, which it will call with the result rather than returning the result:这很棘手,因为你的回复有延迟
返回数据之前需要等待SQL响应,
这就是为什么需要传递回调函数
this is tricky because you have a delayed response
you need to wait the SQL response before return data,
that's why need to pass a callback function
请参阅网站:groups.google.com/forum/?fromgroups#!topic/phonegap/YCRt2HducKg
}
与以下 HTML 相关:
以及表格:Unites
A+
See the site: groups.google.com/forum/?fromgroups#!topic/phonegap/YCRt2HducKg
}
related to the following HTML:
with the table: Unites
A+