Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

92
Vistas
How to make variables accessible across multiple get requests in express? And is there a better way to code this?

I have the following get request where I call a bunch of data and pass it through to my EJS view.

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

Two questions:

  1. I have multiple get requests that requires the same information. Is there a way to make this data available across the entirety of my site, so I don't have to rewrite this for each get path?

  2. Is there a more succinct way to write the existing code I have? Perhaps looping through them or something of the sort? Simply for learning purposes.

The code currently works as-is.

Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If the data is constant, you can try this:

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda