4

I am trying to get the value from an inner function. Why is domain always returning undefined? I think this is because the webSQL executes asynchronously. I need to get the value of domain at this point in the program before I can proceed. I think this is a closure problem but perhaps my approach is is just wrong?

var domain = selectDomain();

function selectDomain()
{
    var sql,
        i;

    sql = "SELECT * FROM Domain";

    database.open();
    database.query(sql, [], function(tx, result) 
    {
        for (i = 0; i < result.rows.length; i++)
        {
            var domain = result.rows.item(i);   
            return domain.Domain;
        }
    });
}

1 Answer 1

3

You're right that the query executes asynchronously, and a return statement here will not work. Instead, in the callback function of the query, call another function that passes the result as a parameter, and continue your program from there.

Edit: I just noticed that you loop through the result, which means domain will be continuously overwritten by each row, and always end up with the value of the last item.

var domain;
selectDomain();

function selectDomain() {
  ...

  database.query(sql, [], function(tx, result) 
  {
    for (i = 0; i < result.rows.length; i++)
    {
      handleResult(result.rows.item(i));
    }
  });
}

function handleResult(result) {
    domain = result.Domain;
    // Continue
}
Sign up to request clarification or add additional context in comments.

Comments

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.