0
var results = null;

function fetchdata(option, callback) {
    var db = window.openDatabase('mydb', '1.0', 'Test DB', 1024*1024),
    selectQuery = "SELECT log FROM LOGS WHERE id = ?";
    db.transaction(function(tx){
            tx.executeSql(selectQuery,[option],function(tx,results){
                if( results.rows.length ) {
                     retval = unescape(results.rows.item(0)['log']);
                }
            var returnValue = callback(retval);
            return returnValue;
            });
    });
}
result = fetchdata(2,function(val){ return val; });
console.log("response***",results);
nanobash
  • 5,419
  • 7
  • 38
  • 56
Ananthan
  • 111
  • 1
  • 1
  • 3
  • 1
    What is your question? – Andy Mar 20 '14 at 13:22
  • You can't return from an asynchronous method. – adeneo Mar 20 '14 at 13:23
  • This is a duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call). You cannot return data from an asynchronous callback function. You must either use the data in the callback or call another function from the callback and pass it the data. This is asynchronous programming and is required when using asynchronous operations. This is a very common mistake or lack of understanding (fourth post on this same issue in the last 24 hrs). – jfriend00 Mar 20 '14 at 13:29
  • Promises anybody? First of all async methods *can* return data, it's just that mostly you'd be trying to process that data when the value isn't resolved. Secondly that's why promises where invented. – Joe Minichino Mar 20 '14 at 13:44

1 Answers1

0

I'm pretty sure this is what you want to do. You pass the value in the callback from your transaction function...

function fetchdata(option, callback) {
  var db = window.openDatabase('mydb', '1.0', 'Test DB', 1024*1024),
  selectQuery = "SELECT log FROM LOGS WHERE id = ?";
  db.transaction(function(tx){
    tx.executeSql(selectQuery,[option],function(tx,results){
      var retval; // I added this line so you don't get an error
      if( results.rows.length ) {
        retval = unescape(results.rows.item(0)['log']);
      }
      callback(retval);
    });
  });
}

And then you can process it when it's returned.

fetchdata(2, function (val) {
  console.log("response***", val);
});
Andy
  • 61,948
  • 13
  • 68
  • 95