0

Hey all I've just been fooling around with the HTML5 Database API and I'm having trouble return the result from a function. Here is what I have.

var list = GetScenarios();

GetScenarios: function()
{

var scenarios;

// get all the scenarios
conn.transaction(function(_t) {

_t.executeSql('SELECT * FROM scenarios', [], function(_tr, _result) {

        scenarios = _result.rows;

    });
});

return scenarios;

}

I manage to get the rows from the db but the rows wont assign to the variable scenarios. I know its a scope thing but I can't think how to return the result from the GetScenatios function.

When I log _result.rows I have the data there but scenario is always undefined;

Any thoughts?

Here is how my js file is setup.

window.MyExtension = (function() 
{

    return ({

    OtherMethod: function() {   


        var list = window.MyExtension.GetScenarios();

    },

    GetScenarios: function() {

         ...see above

    }

}());
7
  • Your code is invalid JavaScript. GetScenarios: function() should be function GetScenarios(). It could be GetScenarios = function() but then it would have to appear before var list = GetScenarios();. Commented Nov 10, 2011 at 1:24
  • @gilly3, correct, except for the last remark: jsfiddle.net/FvdbT Commented Nov 10, 2011 at 1:29
  • @stivlo - Perhaps you misread my comment. function GetScenarios() works, as proven by your jsFiddle. But, GetScenarios = function() does not, as evidenced by this one: jsfiddle.net/FvdbT/1 Commented Nov 10, 2011 at 1:33
  • GetScenarios: function() works. I edited the post to reflect the js file setup Commented Nov 10, 2011 at 1:36
  • @gilly3 yes, I agree with that. hooligan, open your JavaScript console, for instance FireBug, and fix the syntax errors. Commented Nov 10, 2011 at 1:37

1 Answer 1

1

It looks like you are trying to return code from an asynchronous request as though it were synchronous. You need to add a callback parameter to GetScenarios():

function GetScenarios(callback) {
    conn.transaction(function(_t) {
        _t.executeSql('...', [], function(_tr, _result) {
            callback(_result.rows);
        });
    });
}

And change your calling code from:

var list = GetScenarios();
// do something with list

To, this:

GetScenarios(function (list) {
    // do something with list
});
Sign up to request clarification or add additional context in comments.

1 Comment

Perfecto! Thank you so much. Also turns out I have to use window.MyExtension.GetScenario() from within the object. Thanks Heaps

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.