0

I'm under the impression that my variable scope should be correct, but the value isn't getting set. I'm wondering why that might be.

Here's my code:

function getUserStatus() {


    var status;

    function querySuccess(tx, results) {
        var row = results.rows.item(0);
        console.log(row['id']);
        status = {
            question: row['id']
        };
    }

    function errorCB(err) {
        console.log(err);
    }

   db.transaction(function(tx) {
        tx.executeSql('SELECT id FROM calculator ORDER by id ASC LIMIT 1', [], querySuccess, errorCB);
    });

    console.log(status);
    return status;
}

Now, the status variable inside the querySuccess() function is getting set correctly - I am getting a value of 1 for it.

However when I check the second variable of status, outside the scope of the function, I am getting undefined.

Am I misunderstanding Javascript variable scope or declaring my variables incorrectly? I'm new to Javascript.

Steven Matthews
  • 9,705
  • 45
  • 126
  • 232
  • I think it is not the problem with javascript scope. How do you call querySuccess() function. Which was not shown in your code. I think console.log(status); is working before querySuccess() is invoked. That is why you get undefined. Because status doesn't have any initial value. – Tintu C Raju Feb 10 '15 at 04:09
  • You are getting tripped up by asynchronous callbacks that are called sometime LATER. Thus you are doing `console.log(status)` BEFORE the async callback has been called and thus before your status value has been set. Instead, you HAVE to use the value in the callback itself or call a function from that callback and pass it the value. You can't program synchronously like you are when there is an async callback. See this post about the same issue with Ajax calls for lots of ideas on how to deal with this: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – jfriend00 Feb 10 '15 at 04:40

3 Answers3

0

When getUserStatus status is called the functions inside it are defined but not executed so your variable has no value(undefined) which is the value of a var that has not been set.

Paul Zepernick
  • 1,452
  • 1
  • 11
  • 25
0

In your code, you should call the function querySuccess with the parameters in

db.transaction(function(tx) {
        tx.executeSql('SELECT id, women FROM calculator ORDER by id ASC LIMIT 1', [], querySuccess, errorCB);
    });

There are no parameters when you are calling that function.

Sajid
  • 11
  • 2
0

See here: Scope in JavaScript / jQuery

Your code is getting executed async, so the execution is literally returning an undefined value before your query is even successful.

Community
  • 1
  • 1
ryanlutgen
  • 2,951
  • 1
  • 21
  • 31