0

我的代码在 phonegap 应用程序中。在执行 SELECT SQL 语句时,我在将结果传递给父函数的变量时遇到了困难。代码如下所示:

function db_data(query) {
var result_out;
db.transaction(function (tx) {
    tx.executeSql(query, [], function (tx, results) {
        console.log("RETURNED SUCCESSFUL RESULTS"); // SUCCESSFULLY EXECUTING HERE.
        result_out = results.rows;
    }, function (){
        console.log("Error on executing sql");
        result_out = false;
    }); 
});
console.log(result_out); // NOTHING LOGGING HERE.
return result_out;
}

这个函数是传递普通的 SELECT 语句。该函数不返回任何东西,返回的对象仅在 SQL 执行函数中成功记录。

4

2 回答 2

2

该操作是异步的。里面的操作db.transaction可能会在稍后生效。当您记录结果时,它还不存在。

如果您想在获取 的值后执行某些result_out操作,则需要将其放在回调中:

function db_data(query,callback) {
    var result_out;
    db.transaction(function (tx) {
        tx.executeSql(query, [], function (tx, results) {
            console.log("RETURNED SUCCESSFUL RESULTS"); // SUCCESSFULLY EXECUTING HERE.
            callback.call(this,results.rows);
        }, function (){
            console.log("Error on executing sql");
            callback.call(this,false);
        }); 
    });
}

使用 db_data 时,而不是

var result = db_data('your query');
//do something with result

改为这样做

db_data('your query',function(result){
   //do something with result here
   //result will either be a false or the result
});
于 2012-09-10T09:11:23.543 回答
1

那是因为数据库操作是异步的。result_out在执行 sql 之前打印该值。您应该为db_data.

function db_data(query, callback) {
  var result_out;
  db.transaction(function (tx) {
    tx.executeSql(query, [], function (tx, results) {
      console.log("RETURNED SUCCESSFUL RESULTS"); // SUCCESSFULLY EXECUTING HERE.
      callback(null, result.rows); // <<<<<<<<<<< 
    }, function (){
      callback(new Error('error executing sql')); // <<<<<<<<<<<<<
    }); 
  });
}

db_data('select * ....', function (err, rows) {
    // do something with rows
})
于 2012-09-10T09:11:15.840 回答