I'm fairly sure the problem here is simply I'm not thinking in the necessary, asynchronous way yet for Node.js.
I have a function userExists() in a module db which checks whether a user is in a database when passed an email, and returns true or false.
The relevant part:
userExists : function(email) {
var client = new pg.Client(app.conString);
var query;
var result = false;
client.connect();
query = client.query(
"SELECT * FROM users WHERE email = $1",
[email]
);
query.on('row', function(row) {
result = true;
});
query.on('end', function() {
client.end();
return result;
});
I am calling it like this:
if (!db.userExists(req.session.email)) {
newUser();
} else {
updateUser();
}
}
It is always newUser() which is called, whatever userExists() returns. How can I solve this?
You got the time wrong. The queries finishes after you function is run, so you need to pass a callback function and "wait" for the result.
userExists = function(email, cb) {
var client = new pg.Client(app.conString);
var query;
var result = false;
client.connect();
query = client.query(
"SELECT * FROM users WHERE email = $1",
[email]
);
query.on('row', function(row) {
result = true;
});
query.on('end', function() {
client.end();
cb(result);
});
}
// Time 1: ask is the user exists
db.userExists(req.session.email, function(exists) {
// Time 3: Yeah result came back
if (exists) {
updateUser()
}
else {
newUser();
}
});
// Time 2: I've asked, let's wait for the result
// The following code will likely be executed before you get the result back