将多个值从mssql db传递给我的视图

我目前有一个工作代码来查询我的数据库和传递值的节点视图。

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个表,并将所有这些值传递给我的观点吗?

您可以在Node v7 +中使用async / await做一个Promise链:

 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) } }) 

要同时运行Promise.all ,请使用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) } }) 

每个查询返回一个承诺。 要同时运行所有,你可以使用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}) )