I'm new to Node.Js and JavaScript web development on the backend. I see that callbacks inside callbacks could be a pain and there are modules to avoid that. One of these modules is async, https://github.com/caolan/async
I've read the documentation but it is hard to start and understand how to do it.
For example, I've this function "check_aut_user", How can I convert this code using async?
function check_auth_user(username, password, done) {
var client = new pg.Client("pg://user:[email protected]/database");
client.connect(function(err) {
// If not get the connection
if(err) { return console.error('could not connect to postgres', err); }
// Query the user table
client.query('select * from "user" where username = $1 and password = $2', [username, password], function(err, result) {
if(err) { return console.error('error running query', err); }
if (result.rowCount > 0) {
var res = result.rows[0];
console.log(res);
passport.serializeUser(function(res, done) {
//console.log("serializer: " + res);
done(null, res);
});
passport.deserializeUser(function(user, done) {
//console.log("deserializer: " + user['password']);
done(null, res);
});
return done(null, res);
} else {
return done(null, false);
}
});
});
}
Best Regards,
done()
can be called multiple times in your code. Here's some info on understanding callbacks and how they work: javascriptissexy.com/… – Deedradeedsthinking asynchronous
:). As said above it can be moved to review forum. – Vanwinkle