Edit 2018-01-18: Use async/await instead of promise chaining. It will solve all your problems.
I have this code for mongoose in NodeJS
User.find({ name: 'John' })
.then((users) => {
if (!users.length) return res.send('No users found.');
return Request.find({ cost: 100 })
})
.then((requests) => {
console.log('should not get here');
return res.json(requests);
})
.catch((err) => {
res.status(500).json(err);
})
I wish to stop the execution if there are no users found, and just send "No users found." without executing anything else.
I am aware I could use throw res.send('No users found.');
instead.
but then that would make it impossible for me to catch genuine errors - that might happen while saving or updating for example - and manage them.
How should I approach this? Should I use a different code structure? I like how simple and maintainable this structure is, except for this one downside.