Reputation: 5450
I am using NodeJS and Mongoose for an application that has users. And I have a large number of actions the server does on a particular user, depending on the request.
That means, I have this particular code fragment appearing in a lot of functions:
User.findOne({'email':req.user.email}, function (err, user) {
if (err) {
console.log('err');
res.send('Error');
}
if(!user){
console.log('err');
res.send('Error');
}
// do something with returned user
user.data = ....
...
user.save(function(err) {
if(err) {
console.log('err');
res.send('Error');
}
else {
console.log('success');
res.send('Success');
}
}
As you can see, there is a lot of code that replicates. The code that changes is the part 'do something with returned user'. Almost everything else (error messages, etc.) remains same.
So, how can I extract this part out? Since this is working on callback mechanism, is there a certain way to achieve this?
Upvotes: 1
Views: 204
Reputation: 11917
One way is to use Promises. It would involve finding a way to convert the Mongooose api to return Promises instead of using callbacks. After that, you could create code that would follow the lines of
User.findOne(...)
.then((user) => {
// do something with the returned user
return user.save();
}).then(() => {
console.log('success');
res.send('Success');
}).catch(() => {
console.log('err');
res.send('Error');
});
Promises resemble traditional synchronous coding where you can propagate errors akin to try-catch block and thus needing only one error handling location. This way you wouldn't have to replicate the console.log('err'); res.send('Error');
lines in multiple places.
You can read an introduction to Promises for example in "Promises - A Gentle Introduction". For the part on converting Mongoose to Promises there may be an existing module for this, or another approach that APIs use is to not give callback function as the last argument and then a Promise is returned instead. Unfortunately, I don't have exact knowledge in this particular Mongoose API.
Upvotes: 1