0

Hi I am calling a function get_location_tcount(1); whose declaration is like

function get_location_tcount(id,callback) {
    myDB.transaction(function (transaction) {
        var t_sql = 'select * from tbl_locations where location_structure_id = "' + id+ '"';
        transaction.executeSql(t_sql, [], function (tx, results) {
            var length = results.rows.length;
            callback(length);
        }, null);
    });
 }

This how I am calling it

var t_count = 0;
get_location_tcount(1,function(total_count){
    alert(total_count); // Alerting the value
    t_count = total_count; // but not setting in variable t_count
});

and I am using the t_count in

shelfs_list += '<p>Total Count : ' + t_count + '</p>';

I am setting it just after calling the function

  • 1
    `but not setting in variable t_count` You're probably trying to read `t_count` somewhere else in your code before it has been set. Your code is asynchronous. Add a `console.log(t_count);` at the end of your callback, and you'll see that it's actually set when the callback is executed. Possible duplicate of [Why is my variable unaltered after I modify it inside of a function?](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – blex Jan 05 '21 at 11:35
  • just check where I am using t_count i add that snippet too – karan singh chauhan Jan 05 '21 at 11:41
  • _"I am setting it just after calling the function"_ Maybe, but "after" in the code is not the same as "after" in time. Even if the line of code using `t_count` appears after in your code, it's still executed before. `get_location_tcount` is asynchronous. Read the answer at the link I provided above – blex Jan 05 '21 at 11:43
  • @blex I got it now, so I should use setimeout function for this? – karan singh chauhan Jan 05 '21 at 11:53
  • `setTimeout` would probably work but would be a very dirty workaround :) A cleaner solution would be to create a `keepGoing` function (name it something meaningful, this is just an example). That `keepGoing` function would be where you use your variable (`shelfs_list = ...`). And at the end of your callback, right after setting `t_count = ...`, call `keepGoing();` – blex Jan 05 '21 at 12:01
  • No, don't use setTimeout. Just accept that you can never expect a *future* result to be available *now*, and so you should put any code that needs the result inside that callback that you provided to `get_location_tcount`, or call it from within there. – trincot Jan 05 '21 at 12:02
  • @blex thanks for the answer I am now clear about how to use it – karan singh chauhan Jan 05 '21 at 12:07

0 Answers0