0

I want to make a function that return a value of sql result set list (dataLite).the problem is, I can't even read the value of variable(dataLite) outside db.transaction, it will return null value . I am new to javascript and Jquery so I hope I can find an answer here. Here's part of my function

function functionA(){
    var dataLite=null;
    db.transaction(function (tx) {
       tx.executeSql('SELECT * FROM tableA', [], function (tx, results) {
       var len = results.rows.length, i;
       msg = "<p>Found rows: " + len + "</p>";
       alert(msg);
       dataLite=results.rows;   
     }, null);
    });
    alert(dataLite+'>>>');
    return dataLite;
}
  • keeping any connection string on JavaScript is not a good practice at all . Don't keep any sensitive things on client side. Make a call to server side validate and work on that. – Arunprasanth K V Dec 16 '14 at 06:08
  • Asynchronous !== Synchronous. Same answer from this Ajax questrion applies here http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – epascarello Dec 16 '14 at 06:11
  • sorry i don't know about that. I'll read that post first. thanks – ade ignacio Dec 16 '14 at 06:24

1 Answers1

0

You can't return from asynchronous code, the data is not yet available when function returns, it will come later. For such situations (AJAX requests, animations, etc.) you basically have to patterns. The one is callbacks:

function functionA(callback) {
    db.transaction(function (tx) {
        tx.executeSql('SELECT * FROM tableA', [], function (tx, results) {
            callback(results.rows);
        }, null);
    });
}

functionA(function(data) {
    console.log(data);
});

The second one is promise pattern:

function functionA(callback) {
    return new Promise(function(resolve) {
        db.transaction(function (tx) {
            tx.executeSql('SELECT * FROM tableA', [], function (tx, results) {
                resolve(results.rows);
            }, null);
        });
    });
}

functionA().then(function(data) {
    console.log(data);
});

The second one is more powerful and advanced, and gives several additional benefits simple callback don't offer. But in your basic case both will work fine.

Also make sure you read this post on the similar topic.

Community
  • 1
  • 1
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • how could I get the callback value then? for example if I create another function and I need the results.rows to be available in that other function? thanks for the answer though. – ade ignacio Dec 16 '14 at 06:40
  • You would need to use another function inside of the first function callback. `functionA(function(data) { otherFunction(data); });`. – dfsq Dec 16 '14 at 06:48
  • ok thanks a lot. I will also read that post you mentioned above. – ade ignacio Dec 16 '14 at 06:55