0

I have the following code in one of my function. I have an array 'arr' which is working correctly when used inside if{}. But its now working when using outside it. Can anyone point me what I am missing.

 function runQueries()
 {
    var arr = new Array;

    db.transaction (function (transaction) 
      {
        var sql = "SELECT * FROM incomecategory";

        transaction.executeSql (sql, undefined, 
        function (transaction, result)
        {
          if (result.rows.length)
          {
            for (var i = 0; i < result.rows.length; i++) 
            {
              var row = result.rows.item (i);
              var categoryname = row.categoryname;
              arr[i] = categoryname;
            }
                              //alert(arr[0]); // It works


          }  
          else
          {

          }
        }, error);

      });
       //alert (arr[0]); // It doesn't work. 

 }
3
  • open up the error console of your browser, and see if you get any javascript errors Commented Oct 3, 2013 at 20:46
  • Not sure what framework this webSQL-ish code runs under, but they're often asynchronous. That transaction function isn't actually running until after the outer function exits (and so, after the alert call). Commented Oct 3, 2013 at 20:47
  • That's because when you alert(arr[0]) your array is STILL empty. if you alert("a") inside and alert("b") outside, it will alert "b" first and "a" later, when your sql finishes executing. Commented Oct 3, 2013 at 20:48

1 Answer 1

4

It's asynchronous behavior. Your alert at the bottom of the code is probably executed before the database query.

Sign up to request clarification or add additional context in comments.

2 Comments

/agreed. What you need to do is call a callback function that receives your array as a parameter (and does whatever you need it to do with it) inside your "if".
thanks. I understood the problem. Is there any way to delay use of arr so that its used only after database query? using a call back function is an option. but in my case , it will be very complicated. this arr is supposed to hold categories. then I have another function ready which runs another query to hold totals of each categories in another array. then I have third function which calculates percentage. finally fourth function would create graph using values held in these series of arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.