2017-08-03 26 views
1

我目前有一個工作代碼來查詢我的db並將值傳遞給節點中的視圖。從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個表,所有這些值傳遞給我的看法嗎?

回答

2

可以在節點V7 +使用async/awaitPromise鏈:

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

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

我試過第一種方法,並得到以下錯誤:https://pastebin.com/Uwn4A8rC你可能是什麼?即時通訊使用mssql節點模塊連接到mssql服務器 – SSS

1

每個查詢返回的承諾。要同時運行,您可以使用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}) 
    )