pg-promise:在顺序很重要的情况下,获得多个结果集的最佳方法是什么
pg-promise: what would be the best way to obtain multiple results sets where order matters
这是我的原始代码:
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})
})
}
})
所以基本上,我想要一个项目,如果找到了 - 我想收集一些相关数据,即编码器,到单独的结果集中,这样我就可以用 {project: project, codifier : 编码器}.
我知道嵌套的 .then 语句看起来很糟糕...有更好的方法吗?谢谢!
I know that nested .then statements seem bad... Is there a better way to do it? Thank you!
唯一不好的是您没有重新使用数据库连接,为每个查询请求一个新的连接。您应该使用 tasks 跨查询共享连接。
向数据库存储库添加另一种方法的示例 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)
}
});
});
}
或者,如果它不可重复使用,您可以在需要的地方执行任务。
这是我的原始代码:
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})
})
}
})
所以基本上,我想要一个项目,如果找到了 - 我想收集一些相关数据,即编码器,到单独的结果集中,这样我就可以用 {project: project, codifier : 编码器}.
我知道嵌套的 .then 语句看起来很糟糕...有更好的方法吗?谢谢!
I know that nested .then statements seem bad... Is there a better way to do it? Thank you!
唯一不好的是您没有重新使用数据库连接,为每个查询请求一个新的连接。您应该使用 tasks 跨查询共享连接。
向数据库存储库添加另一种方法的示例 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)
}
});
});
}
或者,如果它不可重复使用,您可以在需要的地方执行任务。