Web SQL SELECT 事务返回值 [英] Web SQL SELECT transaction return value

查看:26
本文介绍了Web SQL SELECT 事务返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图调用一个从我的 Web SQL 数据库中选择值的函数.我想将 SELECTED 值返回到父函数内的变量中.但是,变量总是返回空白,无论它是否是全局的.

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.

因为您将能够看到 selectRow 函数中的 console.log 记录了来自数据库查询的正确值,但 console.log 在 initDB 函数中显示为空白.

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.

我还注意到在 selectRow 函数中的日志之前显示了空白日志.我发现论坛上的人们都在谈论数据库事务是异步的.我知道这就是为什么我返回的变量为空的原因.然而,在多次撞墙之后,我仍然找不到解决这个异步问题的方法.

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;
}

推荐答案

你可以改变你的 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:

/** Initialize Database  **/
function initDB(){ 
   createTable();
   selectRow("SELECT * FROM planets;", function(pleaseWork) {
     console.log(pleaseWork);
     // any further processing here
   });
}  

/** Select Row from Table **/ 
function selectRow(query, callBack){ // <-- extra param
   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);
         callBack(result); // <-- new bit here
      }, errorHandler);
   });
} 

这篇关于Web SQL SELECT 事务返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆