0

I am trying to fetch user data during a login process. Data stored in rethinkDb. The flow is:

• Request is routed to a controller (via express)

• Controller choose correct handler

• Handler call the dao.get():

  login: function (email, password, res) {
        var feedback = daouser.get(email);
        if (feedback.success) {
            var user = feedback.data;
            //Do some validatios...
        }       
        res.status = 200;
        res.send(feedback);
    },

• dao.get() code is:

get: function (email) {        
    var feedback = new Feedback();
    self.app.dbUsers.filter({email: email}).run().then(function (result) {
        var user = result[0];
        feedback.success = true;
        feedback.data = user;
        return feedback;
    });
}

But since the call is via a promise, the dao.get return before the actual “Then” function is call and the controller gets undefined feedback…

Something wrong with my design…

Ronen
  • 807
  • 1
  • 13
  • 33

1 Answers1

1

var feedback = daouser.get(email);

You can't do a synchronous assignment here, since .get is asynchronous. Also, notice that you are not returning anything from .get, that's why it's undefined. I'd make all of this a promise chain.

get: function (email) {        
var feedback = new Feedback();

// RETURN is important here, this way .get() return a promise instead of undefined
return self.app.dbUsers.filter({email: email}).run().then(function (result) {
    var user = result[0];
    feedback.success = true;
    feedback.data = user;
    return feedback;
});

}

login: function (email, password, res) {
    //return the promise again, so login will be chainable too
    return daouser.get(email)
    // You can chain another then here, because you returned a promise from .get above
    // Your then function will be called with the return from the previous then, which is 'feedback'
    .then(function(feedback) {
      if (feedback.success) {
        var user = feedback.data;
        //Do some validatios...
      }       
      res.status = 200;
      res.send(feedback);
  }
},
marton
  • 1,300
  • 8
  • 16