2

I've made a function myFunction which performs simple task i.e. to retrieve data from sqlite database and save it in a array which can be used easily. This function should follow these steps to fulfill my functionality.

  1. To retrieve data from database.
  2. To save it into array.
  3. return array

But it is performing these steps in this sequences; 3, 1, 2, so I am not getting the data because it returns without getting it.

e.g.

function myFunction() {
    var ret;
    var arr = [];

    db.transaction(function (trans) {
        trans.executeSql('SELECT * FROM tblname', [],
            function (transaction, result) {
                if (result != null && result.rows != null) {
                    for (var i = 0; i < result.rows.length; i++) {
                        var row = result.rows.item(i);
                        ret = row.urlcolmn;
                        arr.push(ret);

                        alert('alert 1'); // just to check which line(alert) is called first
                    }
                }
            }, errorHandler);
    }, errorHandler, nullHandler);

    alert('alert 2'); // just to check which line(alert) is called first

    return arr;
}

In above code alert 2 is shown before alert 1..... that's why it doesn't return value in array. This problem can be because sqlite in JS is Asynchronous.

Paul S.
  • 64,864
  • 9
  • 122
  • 138
Andro
  • 21
  • 2
  • possible 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) – Andreas Oct 21 '13 at 12:27
  • 1
    You can't `return` like this from an _asynchronous_ function, you have to employ a callback. – Paul S. Oct 21 '13 at 12:30
  • @PaulS. Thanks for replying... Is there any method to make it synchronous... I was facing same problem in ajax function too but I set **async:false** there and then It's working fine....I was using ajax function for getting content from URL... Please help me regarding this. – Andro Oct 21 '13 at 12:40
  • 1
    As far as I know, no. You will most likely have to refactor your code to work in an asynchronous environment – Paul S. Oct 21 '13 at 12:52

0 Answers0