![](/img/trans.png)
[英]EJS: How can I render two or more populated colletions from mongoose in EJS file
[英]make two db calls and render the content of two different array populated by the results in one ejs page
我正在嘗試表達,我必須渲染一個傳遞兩個 arrays 的頁面,該頁面由兩個 DB 調用填充,查詢是正確的,事實上,如果我在 ejs 頁面中只渲染一個數組,它會傳遞內容。
當我傳遞一個數組時,我會這樣做:
dao.getAllSerie().then((show) => {
res.render('index', {
series: show,
})
}).catch(() => res.status(500).end());
如果我這樣做一切順利並且沒有任何問題,則呈現內容並且 ejs 頁面充滿了價值。
需求是:“如果我必須渲染兩個 arrays,其中充滿了對 DB 的兩個不同調用的兩個結果,我該怎么辦?”
我試過這個:
app.get('/', (req, res) => {
series = [];
categories = [];
//CALL TO A FUNCTION THAT SELECT FROM DB ASSIGN THE RESULT TO 'SERIES'
dao.getAllSerie().then((show) => { series = show; })
.catch(() => res.status(500).end());
//CALL TO A FUNCTION THAT SELECT FROM DB ASSIGN THE RESULT TO 'CATEGORIES'
dao.getCategorie().then((category) => { categories = category; })
.catch(() => res.status(500).end());
//IN THE RENDER PAGE EACH 'CATEGORIES' AND 'SERIES' ARE NULL
res.render('index', {
series: series,
categories: categories
})
})
但是無論是系列還是類別都會導致 null ,這意味着在沒有動態內容的情況下呈現 ejs 頁面。
我認為是某種異步問題,有人知道這是否可能以及如何?
這里的數據庫調用函數:
//GET OF ALL SERIES IN THE DB
exports.getAllSerie = function() {
return new Promise((resolve, reject) => {
const sql = 'SELECT * FROM serie';
db.all(sql, (err, rows) => {
if (err) {
reject(err);
return;
}
resolve(rows);
});
});
};
//GET OF ALL CATEGORIES IN THE DB
exports.getCategorie = function() {
return new Promise((resolve, reject) => {
const sql = 'SELECT DISTINCT categoria FROM serie';
db.all(sql, (err, rows) => {
if (err) {
reject(err);
return;
}
resolve(rows);
});
});
};
我知道類別應該在一個單獨的表格中,但這只是為了嘗試一下。 提前感謝大家的時間。 真的很感激
您需要將 2 個異步函數存儲在一個數組中,然后使用 Promise.all 等待所有異步調用返回,然后只渲染頁面:
app.get('/', (req, res) => {
let dataFetchers = []
dataFetchers.push(dao.getAllSerie) // the first async function
dataFetchers.push(dao.getCategorie) // the second
Promise.all(dataFetchers) // will wait for ALL promises to resolve or reject
.then(dataArray => {
let series = dataArray[0] // the first promise's result
let categories = dataArray[1] // the second
res.render('index', { // render only once you have ALL the datum
series: series,
categories: categories
})
})
.catch(err => res.status(500).end())
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.