here is my naive code:
db.projects.find_one(project_id, user_id)
.then(project => {
if (!project) {
req.flash('info', 'Project not found');
res.redirect('./projects');
} else {
db.codifier.get(project.project_id)
.then(codifier => {
codifier = build_codifier(codifier);
res.render('project', {project: project, codifier: codifier})
})
}
})
So basically, I want to get a single project, and if it is found - I want to gather some relative data, which is codifier, into separate result set, so I can render with {project: project, codifier: codifier}.
I know that nested .then statements seem bad... Is there a better way to do it? Thank you!
I know that nested .then statements seem bad... Is there a better way to do it? Thank you!
It is only bad because you do not re-use the database connection, requesting a new one for each query. You should use tasks to share the connection across queries.
See Chaining Queries.
Example of adding another method to your database repository class:
getCodifier(project_id, user_id) {
// use the repository object object
return this.db.task(t => {
// you can access repository methods on the context here:
return t.projects.find_one(project_id, user_id)
.then(project => {
if (project) {
return t.codifier.get(project.project_id)
}
});
});
}
Or, if it is not reusable, you can do the task where it is needed instead.