我目前有一个工作代码来查询我的数据库并将值传递给节点中的视图。
router.get('/', function(req, res, next) {
sql.connect(config).then(() => {
return sql.query`select Project_Type_Desc from Project_Type`;
}).then(result => {
res.render('newProject', {projects: result});
}).catch(err => {
console.log(err);
})
});
但是有些人可以告诉我如何查询4个表并将所有这些值传递给我的视图吗?
答案 0 :(得分:2)
您可以在Node v7 +中使用Promise
/ async
建立await
链:
router.get('/', async (req, res, next) => {
await sql.connect(config)
try {
const projects = await sql.query(`select Project_Type_Desc from Project_Type`)
const result2 = await sql.query(`another query`)
const result2 = await sql.query(`another query`)
const result4 = await sql.query(`another query`)
res.render('newProject', {
projects,
result2,
result3,
result4
})
} catch (error) {
console.log(error)
}
})
要同时运行Promises,请使用Promise.all
:
router.get('/', async (req, res, next) => {
await sql.connect(config)
const promises = Promise.all([
await sql.query(`select Project_Type_Desc from Project_Type`),
const result2 = await sql.query(`another query`),
const result2 = await sql.query(`another query`),
const result4 = await sql.query(`another query`)
])
try {
const [projects, result2, result3, result4] = await promises
res.render('newProject', {
projects,
result2,
result3,
result4
})
} catch (error) {
console.log(error)
}
})
答案 1 :(得分:1)
每个查询都会返回一个promise。要同时运行所有,您可以使用Promise.all()
,这将在它们全部返回时触发响应。例如:
sql.connect(config)
.then(() => {
const projectPromise = sql.query`select Project_Type_Desc from Project_Type`
const otherTablePromise = ...
const anotherTablePromise = ...
return Promise.all(
projectPromise,
otherTablePromise,
anotherTablePromise
)
})
.then(([projectResult, otherResult, anotherResult]) =>
res.render('newProject', {projects: result})
)