[英]Iterate through data and send as response
I am trying to take data, send that to an API, take data out of that and pass it on as a response. 我试图获取数据,将其发送到API,从中获取数据,并将其作为响应传递。 Currently i see the data in my terminal, but my response object is empty.
目前,我在终端中看到了数据,但响应对象为空。
//Make API call to get the match data
var matches = await api.get(`${platform}1`, 'match.getMatchlist', player.accountId)
//Check for errors and send 404 if errrs are found
if(matches.length >0) {
return res.status(404).json({
message: 'No summoner found'
})
}
//Due to large amount of data, splice entries to keep responses smaller and more manageable
var splice = matches.matches.splice(0 , 2);
var matchData;
//Itterate through
splice.forEach((m) => {
api.get(`${platform}1`, 'match.getMatch', m.gameId)
.then((data) => {
console.log(data.gameId)
matchData = data.gameId;
})
});
res.json({
data: matchData
})
In my terminal, I get the expected data : 在我的终端中,我得到了预期的数据:
4114813378
4104452309
This shows that the API call is working and providing me with the correct ata but the data is lost between then and the res.json({}) 这表明该API调用正在正常工作,并向我提供了正确的ata,但是在那之后和res.json({})之间的数据丢失了
I've tried pushing it to an array instead, but this also leaves my response eempty. 我尝试将其推到数组中,但这也使我的响应无能为力。
You need to use Promise.all
in the following manner; 您需要通过以下方式使用
Promise.all
;
userCtr.getGems = async (req, res) => {
try {
const matches = await api.get(`${platform}1`, 'match.getMatchlist', player.accountId);
// Check for errors and send 404 if errrs are found
if (matches && matches.length) {
return res.status(404).json({
message: 'No summoner found',
});
}
// Due to large amount of data, splice entries to keep responses smaller and more manageable
const splice = matches.matches.splice(0, 2);
const promises = [];
splice.forEach((m) => {
promises.push(api.get(`${platform}1`, 'match.getMatch', m.gameId));
});
const result = await Promise.all(promises);
const gemIds = result.map((r) => { return r.gameId; });
return res.staus(200).json({ data: gemIds });
} catch (err) {
logger.error(err);
return res.status(500).json({ error: 'Internal server error' });
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.