我有以下獲取請求,我在其中呼叫一堆資料并將其傳遞給我的 EJS 視圖。
router.get('/currentrentals', ensureAuthenticated, async (req, res) => {
const companies = await Company.getCompanies();
const barges = await Barge.getBarges();
const parishes = await Parish.getParishes();
const states = await State.getStates();
const pickupdropoff = await PickupDropoff.getPickupDropoff();
var notifications = await Notification.getNotifications();
JSON.stringify(barges);
JSON.stringify(companies);
JSON.stringify(parishes);
JSON.stringify(states);
JSON.stringify(pickupdropoff);
JSON.stringify(notifications);
var notifications = await notifications.sort((a, b) => b.id - a.id).slice(0,3);
res.render('currentrentals', {
name: req.user.name, companies: companies, barges: barges, parishes: parishes, states: states, pickupdropoff : pickupdropoff, notifications : notifications
});
}
);
兩個問題:
我有多個需要相同資訊的獲取請求。有沒有辦法讓這些資料在我的整個網站上可用,所以我不必為每個獲取路徑重寫它?
有沒有更簡潔的方法來撰寫我現有的代碼?也許回圈通過它們或類似的東西?只是為了學習目的。
該代碼目前按原樣作業。
謝謝!
uj5u.com熱心網友回復:
如果資料是不變的,你可以試試這個:
let data = null;
async function getData() {
if (!data) {
data = {
companies: await Company.getCompanies(),
barges: await Barge.getBarges();
parishes: await Parish.getParishes(),
states: await State.getStates(),
pickupdropoff: await PickupDropoff.getPickupDropoff(),
notifications: (await Notification.getNotifications()).sort((a, b) => b.id - a.id).slice(0,3)
};
}
return data;
}
router.get('/currentrentals', ensureAuthenticated, async (req, res) => {
res.render('currentrentals', { name: req.user.name, ...(await getData()) });
}
);
// other routes
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/450037.html
標籤:javascript 节点.js 表示 ejs knex.js
