E
E
Egor2014-03-14 18:07:24
MongoDB
Egor, 2014-03-14 18:07:24

How to carry out data transfer in a chain of asynchronous functions?

I'm just getting started with Node.js. Due to asynchrony, I encountered a problem when working with the database.
For the database, I use mongoDB + mongoose on the node.
A little about architecture.
reqHandlers.js - here are methods for handling requests.
dbHandlers.js - here are methods for working with DB. These methods cannot affect the request in any way. Only return data from the database or error text.
Task: Get data from the database from the user and then somehow use them.
As a result, the following code was born:
reqHanders.js file - request processing

function login(req,res,next) {
  var auth = req.body.auth;
  var promise = new Q;

promise.then(dbHandlers.login(auth.login.toLowerCase(),auth.password))
            .then(function makeSmt(user){
        console.log("Q: "+user); //как организовать код, чтобы в переменной user лежали данные полученные из БД?
       });
}

dbHandlers.js file - database query
function login(login,password){

  var connection = mongoose.connection;
  if(!connection) return null;

  var users = User.users;

  users.find({'login':login,'password':password},function(err,user){		
    if(err){
      console.error(err.stack);
      //req.emit('error','userIncor');
      return;
    }
    if(user.length === 0){
      //req.emit('error','userIncor');
      return;
    }
    //req.emit('success',user[0]);
    return;
  });
}

The question is how to organize the code so that the user variable contains data obtained from the database.
I suspect that I do not use all the features of Q. I will be glad for advice and links.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri Shikanov, 2014-03-15
@ByKraB

Use async and you will be happy.

C
corristo, 2014-03-16
@corristo

Well, or Promises / A +, as an option

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question