2

I am using Lawnchair to save data in js and retrieve it back for my mobile app.

I have this in my js file.

$(document).ready(function() {

    //Lawchair set up
    db = Lawnchair({name: 'db'},function(e){
      console.log('storage open');
    });

    //store the 'username' key in storage
    db.save({key:"username", value: "john"});

    var name = ""
    db.get("username", function(obj){
            name = obj.value;
    })

    alert(name);

});

The problem is I always get "" in the name. I can never set any variable inside the callback function of "get" from Lawnchair object. Am I missing something?

Any help would be appreciated.

Thanks.

Phyo Wai Win
  • 1,160
  • 6
  • 14

1 Answers1

3

The database operation is asynchronous. Put your alert inside the callback to the ".get()" function.

As a general rule, any time you see a JavaScript API like this:

something(param, param, ... , function(result, result, ...) {
  // ...
});

it's a good bet that the function may be an asynchronous mechanism, and that the callback function you supply will only be called later when an event actually transpires. In those cases you have to structure your own code such that activities you need to perform after the operation completes are done in code inside the callback.

(It's not always the case; some functional programming APIs for example take functions as arguments.)

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • You are right about that being 'asynchronous'. But still it will be a painful process to put my code in the call back every time I need access some data from storage. I am now looking into how I can wait in the js until the variable has been set after the async operation. Might not be ideal. But still I need to create a getData("somekey") method. Thanks. – Phyo Wai Win Feb 14 '12 at 15:13
  • There's generally no way to "wait" in client-side JavaScript. – Pointy Feb 14 '12 at 17:15