Estoy creando un sitio web que usa una API para mostrar los resultados de fútbol (fútbol), accesorios, etc. Intenté crear una variable global para guardar los datos solicitados y luego pasarlos a ejs, sin embargo, esto no parece funcionar.
router.get('/stats', (req, res) => {
request(options, function (error, response, body) {
if (error) throw new Error(error);
top_scorer_data = JSON.parse(body)
});
request(options2, function (error, response, body) {
if (error) throw new Error(error);
top_assists_data = JSON.parse(body)
});
request(options3, function (error, response, body) {
if (error) throw new Error(error);
top_red_cards_data = JSON.parse(body)
});
request(options4, function (error, response, body) {
if (error) throw new Error(error);
top_yellow_cards_data = JSON.parse(body)
});
res.render('bundesliga/stats', {})
})
Debe seguir el principio DRY y mover la request a un servicio o una función auxiliar.
No debe usar variables globales, use promesas en su lugar y espere a que finalicen todas las solicitudes.
Por lo tanto, debe prometer el método de solicitud (realmente debe migrar a axios o node-fetch , porque la request está obsoleta)
y luego use Promise.all para realizar todas las solicitudes con cada opción, y luego recopile los resultados en variables, que luego pasa al método .render .
Prueba esto:
router.get('/stats', async(req, res) => {
function getData(options) {
return new Promise((resolve, reject) => {
request(options, function(error, response, body) {
if (error) reject(error);
resolve(JSON.parse(body));
});
});
}
const [top_scorer_data, top_assists_data, top_red_cards_data, top_yellow_cards_data] = await Promise.all([
getData(options),
getData(options2),
getData(options3),
getData(options4)
]).catch(err => {
console.log('err', err);
});
res.render('bundesliga/stats', {
top_scorer_data,
top_assists_data,
top_red_cards_data,
top_yellow_cards_data
});
});