Javascript running "out of order" Javascript running "out of order" express express

Javascript running "out of order"


You need to read up on callbacks, because node programming is all about callbacks.

When you call DoesUserExist(), it calls mongo.connect() and immediately returns. (You can put "console.log('hi')" at the end of DoesUserExist() to verify it's called before your "if count > 0" code.) The Mongo.connect() routine takes a callback, so it is not a simple synchronous function. It calls that function (as a callback) only when the results of the query are ready. Therefore, the "return" isn't returning from DoesUserExist, but from your anonymous function passed to the mongo driver.

Instead of "return true/false", you need to call you "res.redirect" logic. You can do this by taking the "if/then" code in user.create and turn it into an anonymous function. Pass that to DoesUserExist(), which will call it in the "count" callback.

When the "count" callback runs and calls your anonymous function, it will have: 1) the value of count, and 2) the req/res object to do the redirect on.

I could write the code for you, but it's really something you need to play with and read up on until you get the "aha" moment to understand all callbacks.