So I am completely new to node and I am trying to complete a simple web app for a class. Essentially I have some code that wants to add a user to the database and depending on whether the addition to the database was successful or whether the password was wrong or the username is longer than 128 char then I want to return a value. So dude in my example is acting as that value. and I wanted to return dude = 100 or whatever I set it to but dude continues to be 0. How do I go about "waiting" so that dude can be 100 that doesn't involve a settimeout. Thanks!
exports.add= function (user, password) {
var dude = 0;
User.findOne({'local.user' : user, function(err, current_user) {
dude = 100;
});
return dude;
}
This is a pretty common problem for new users of asynchronous programming. What you're trying to do is return a value from a synchronous function which depends on the outcome of an asynchronous function. In this case, return dude is actually called before you ever set dude = 100;. You'll need to accept a callback to that add function which can be called once the add is complete. Something like the following:
exports.add = function (user, password, done) {
User.findOne({'local.user' : user, function(err, current_user) {
done(err, 100); // pass the err and code to the callback
});
}
Zooming out a bit, this is how you would use your new module.
var User = require('./user'); // load the module defined above.
User.add(user, password, function(err, code) {
if(err || code === 123) {
// Do something here.
}
});
This defines an inline function which is called when User.add is done adding the user. Zooming out a bit more (assuming Express) would look something like:
var User = require('./user'); // load the module defined above.
app.post('/user/', function(req, res) {
var user = buildUserFromReq(req);
var password = req.body.password;
User.add(user, password, function(err, code) {
if(err) {
return res.send('cannot add user', err);
}
res.send('user added');
});
});