0

Am having trouble to update a variable, am getting undefined when I can see the content, am trying to keep the value of the variable data[0] outside the then() function, and finally add to a $scope variable.
My code is this:

var user = function(){
      var usuario;
      var uno = MGAindexdb.regresarUsr().then(function(data){
        console.log('Dentro de usr');
        console.log(data[0]); // here I see the object with it's content
        usuario = data[0]; // copy the value to usuario
        console.log(usuario); // same data with the object
      }).catch(function (e) {
      log(e, "error");
      });
      console.log(usuario); // print undefined
    }
  user();
  // This is how the content looks like in dev chrome tool: 
  // Object {usr_id: 45, nombre: "jose", email: "[email protected]", fb_email: "[email protected]", registration_date: "2014-05-31T18:03:33.000Z"…}

I read this article that explains how closures work and i think it wasn't exactly my case and also read this great post that explains javascript scope. But still can't figure out why the value is not been saved. Thanks in advance for your time.

12
  • It is an async operation, so console.log(usuario); runs before the promise then chain callback is run which sets the data to usuario. You must return promise from user function and let the consumers chain through to get the data. See this as well. Commented Jan 20, 2015 at 20:15
  • Am getting that data from a factory in services.js and am not using any promise to get that data Commented Jan 20, 2015 at 20:23
  • Regardless, your question is more specific to accessing data from an async callback. Linked answer will give you more details on that. Commented Jan 20, 2015 at 20:24
  • app.factory('MGAindexdb', function (jsonService, $q) { var db = new Dexie("MGADT"); db.version(1).stores({ users: "++id,usr_id,nombre,email,fb_email,registration_date,validated,membership,amount,last_access,key,is_logged_in,imagenDeUsuario,total,meQueda,gastoDia" }); db.open(); return { regresarUsr: function () { return db.transaction("rw", db.users, function () { return db.users.orderBy('nombre').toArray(); }); } } }); And to get the data in usuario is the code posted before from the dashboard Commented Jan 20, 2015 at 20:25
  • and I already try the solution proposed: .then(function(data) { $scope.usuario = data[0]; }) But still got undefined Commented Jan 20, 2015 at 20:27

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.