[英]How do I take data from multiple node-request bodies and pass into an EJS file
I am creating a website which uses an api to dispaly football (soccer) scores, fixtures etc. I have tried to create a global variable to save the request data to and then pass into ejs however this doesn't seem to work.我正在创建一个网站,它使用 api 来显示足球(足球)比分、赛程等。我试图创建一个全局变量来将请求数据保存到然后传递给 ejs,但这似乎不起作用。
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', {})
})
You should follow DRY principle and move request
to a service or a helper function.您应该遵循 DRY 原则并将
request
移动到服务或助手 function。 You shouldn't use global variables, use promises instead, and wait for all requests to finish.您不应该使用全局变量,而是使用 Promise,并等待所有请求完成。
So, you should promisify request method (you should really migrate to axios
or node-fetch
, because request
is deprecated)所以,你应该承诺 request 方法(你应该真正迁移到
axios
或node-fetch
,因为request
已被弃用)
and then use Promise.all
to make all the requests with each option, and then gather results into variables, which you then pass to the .render
method.然后使用
Promise.all
使用每个选项发出所有请求,然后将结果收集到变量中,然后将其传递给.render
方法。
Try this:尝试这个:
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
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.