简体   繁体   English

在嵌套函数结构中访问JavaScript父函数变量

[英]Access JavaScript parent function variable in nested function structure

My Code is in phonegap application. 我的代码在phonegap应用程序中。 While executing a SELECT SQL statement, I am experiencing difficulties to pass the results to parent function's variable. 在执行SELECT SQL语句时,我很难将结果传递给父函数的变量。 The code is represented below: 代码如下所示:

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

This function is to pass common SELECT statements. 此函数用于传递常见的SELECT语句。 The function is not returning any thing and the returning object is successfully logged only within the SQL execution function. 该函数不返回任何东西,并且仅在SQL执行函数中成功记录了返回对象。

The operation is asynchronous. 该操作是异步的。 The operation inside db.transaction may take effect in a later time. db.transaction内部的操作可能会在以后生效。 By the time you logged the result, it isn't there yet. 在您记录结果时,它还不存在。

If you want to execute something after getting a value for result_out , you need to put it inside the callbacks: 如果要在获取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);
        }); 
    });
}

when using db_data, instead of 使用db_data时,代替

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

do this instead 改为这样做

db_data('your query',function(result){
   //do something with result here
   //result will either be a false or the result
});

That's because the db operations are asynchronous. 这是因为db操作是异步的。 The value result_out is printed before the sql has been executed. 在执行sql之前将打印结果result_out You should provide a callback function for db_data . 您应该为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
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM