Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

91
Views
¿Cómo hacer que las variables sean accesibles a través de múltiples solicitudes de obtención en express? ¿Y hay una mejor manera de codificar esto?

Tengo la siguiente solicitud de obtención en la que llamo a un montón de datos y los paso a mi vista 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 }); } );

Dos preguntas:

  1. Tengo varias solicitudes de obtención que requieren la misma información. ¿Hay alguna manera de hacer que estos datos estén disponibles en todo mi sitio, de modo que no tenga que volver a escribir esto para cada ruta de obtención?

  2. ¿Hay una forma más sucinta de escribir el código existente que tengo? ¿Quizás recorrerlos o algo por el estilo? Simplemente con fines de aprendizaje.

El código actualmente funciona como está.

¡Gracias!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Si los datos son constantes, puedes probar esto:

 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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!