user2425138
user2425138

Reputation: 89

How return var from callback function ? OOP property

var App = function(){
   this.db = [];
}
App.prototype.getJson = function(){
   var slef = this;
   $.getJSON('url', function(data){
       self.db.push(data);
     });
}

$(document).ready(function(){
   var app = new App();
   console.log(app.db); //return []
   setTimeout(function(){
      console.log(app.db); //return data JSON
   }, 5000);
});

Why is this happening? How get property app.db without setTimeout?

AND

Can i return variable from callback function without constriction

appAPI.db.async.get(key, function(value) {
        var data = (value === null) ? null : JSON.parse(value);
        // invoke the callback and pass the results to it
        callback(data);
    });

and

LB.getData('user', function(data) {
    // use the data here
    alert(data.someProperty);
});

?

Upvotes: 0

Views: 245

Answers (1)

Vladimir Gordienko
Vladimir Gordienko

Reputation: 3470

it cause because you do assync request, use promices to get value after request is end. http://api.jquery.com/promise/

setTimeout(function(){
     console.log(app.db); //return data JSON
}, 5000);

donot save you if request will be longer then 5sec

sample:

var App = function(){
   this.db = [];
}
var dfd = new jQuery.Deferred();
App.prototype.getJson = function(){
   var slef = this;
   $.getJSON('url', function(data){
       self.db.push(data);
       dfd.resolve(data);
     });
}

$(document).ready(function(){
   var app = new App();
   console.log(app.db); //return []
   $.when( dfd.promise()).then(
      function( data) {
        console.log(app.db);
      }
    );
});

Upvotes: 1

Related Questions