Pretty sure I could do this with async/await just fine, but I'd like to understand how to implement this logic without.
Workflow:
- Find a job in the database
- if the job exists, find a Person, if not, send a response to the frontend
- then do Person logic
Code:
Job.findByPk(jobId)
.then(job => {
if(job) return Person.findOne(...)
else res.status(404).json(...)
})
.then(person => {
if(person)
// Do person logic here
})
.catch(err => ...);
The problem is that this logic obviously doesn't work. The person
parameter in the second .then()
block could be undefined if either no job or no person is found.
So a solution would be to do this in the first .then()
block:
.then(job => {
if(job) // store the job locally
else res.status(404).json(...)
return Person.findOne(...)
})
but that means that the database is searched regardless of if a Job is found or not rather than being conditional on a job being found
How do structure this in a way that makes more sense?
Thanks