Reputation: 1364
I have a nodejs export like this
exports.add = function(req){
var newUser = new User({
email: req.body.email,
password: req.body.password,
});
// Attempt to save the user
newUser.save(function(err) {
if (err) {
return true;
}
return false;
});
}
But it's giving as undefined when i call the function like this
var value = instance.add(req);
Here instance is the imported instance of the javascript file
Upvotes: 1
Views: 816
Reputation: 5345
As stated in comments by @Ben Fortune you couldn't simply return a value from an asynchronous function call. you should use callbacks or promises:
The callback way:
exports.add = function (req, callback) {
var newUser = new User({
email: req.body.email,
password: req.body.password,
});
// Attempt to save the user
newUser.save(function(err) {
if (err) {
callback(err, null);
}
callback(null, newUser.toJSON()) ;
});
}
Then:
instance.add(req, function(err, value) {
if (err) throw err;
// use value here
});
Read More: How do I return the response from an asynchronous call? And implement promise way if you prefer.
Upvotes: 1