I don't have much experience in async code and I'm stuck with a problem, here is my code :
if (!req.params.user_name) {
req.params.user = req.me;
} else {
User.findOne({username: req.params.user_name}, '_id', (error, user) => {
if (error) {
return next(error);
}
if (!user) {
let error = new Error('User not found');
return next(error);
}
req.params.user = user;
});
}
Account.findOne({name: req.params.account_name, created_by: req.params.user})
.populate(['currency', 'created_by'])
.exec((err, account) => {
if (err) {
return next(err);
}
return res.send(account);
});
As you can see the problem is that in one case I just have a simple procedural action to do, in the other I have to query the database which is async, then I have to execute the code below. I can't just simply put the Account query in the callback of the User query because I don't need to execute User query all the time. I've tried to find an answer here but the only results I've found are about executing one async task or another (ex: Working with promises inside an if/else). Following the recommandations on this post I've thought about wrapping the code inside the if block in an anonymous function and do something like:
let get_user;
if (!req.params.user_name) {
let get_user = () => {req.params.user = req.me};
} else {
let get_user = User.findOne({username: req.params.user_name}, '_id', (error, user) => {
if (error) {
return next(error);
}
if (!user) {
let error = new Error('User not found');
return next(error);
}
req.params.user = user;
});
}
get_user().then(() => {
Account.findOne({name: req.params.account_name, created_by: req.params.user})
.populate(['currency', 'created_by'])
.exec((err, account) => {
if (err) {
return next(err);
}
return res.send(account);
});
});
But I find it weird and I guess I would need to return a Promise from the anonymous function in the if block.
So what would be an elegant way of solving this ? I'm learning node.js on my free time and any general suggestions would be greatly appreciated.
Thanks for your time.