SSS
SSS

Reputation: 57

Passing multiple values to my view from mssql db

I currently have a working code to query my db and pass values to the view in node.

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

However can some one show me how to query 4 more tables and pass all those values to my view please?

Upvotes: 1

Views: 52

Answers (2)

Miguel
Miguel

Reputation: 20633

You can do a Promise chain using async / await in Node v7+:

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

To run Promises concurrently, use 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)
  }
})

Upvotes: 2

csander
csander

Reputation: 1380

Each query returns a promise. To run all concurrently, you can use Promise.all(), which will trigger a response when they have all returned. For example:

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

Upvotes: 1

Related Questions