IvenMS
IvenMS

Reputation: 535

Access JavaScript parent function variable in nested function structure

My Code is in phonegap application. While executing a SELECT SQL statement, I am experiencing difficulties to pass the results to parent function's variable. 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. The function is not returning any thing and the returning object is successfully logged only within the SQL execution function.

Upvotes: 0

Views: 949

Answers (2)

Joseph
Joseph

Reputation: 119847

The operation is asynchronous. The operation inside db.transaction may take effect in a later time. 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:

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

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

Upvotes: 2

qiao
qiao

Reputation: 18219

That's because the db operations are asynchronous. The value result_out is printed before the sql has been executed. You should provide a callback function for 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
})

Upvotes: 1

Related Questions