0

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!

  • No, nested `then` statements are not necessarily bad, as long as you `return` them properly so that you can chain upon them. in your case - an asynchronous call in a condition - they're even quite unavoidable. – Bergi Jan 01 '18 at 17:28
  • You can try the approach similar to this one: https://stackoverflow.com/questions/39805736/get-join-table-as-array-of-results-with-postgresql-nodejs – vitaly-t Jan 01 '18 at 17:48

1 Answers1

1

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.

vitaly-t
  • 24,279
  • 15
  • 116
  • 138