Weird behavior in TS api endpoint

Currently working on an api endpoint that fetches data from an external api and performs some updates then stores locally.
Solution:
```ts POST = async(request) => { fetch initial data... const players: Map<string, Player> = new Map(); const teams: Map<string, Team> = new Map();...
Jump to solution
2 Replies
Arctic
Arctic8mo ago
Current function structure is as follows:
POST = async(request) => {
fetch initial data...
const players: Map<string, Player> = new Map();
const teams: Map<string, Team> = new Map();
await(async() => {
initialData.forEach((match) => {
validatematch()
if(matchisvalid){
match.stats.forEach((stat) => {
stat.stats.teams.forEach((team) => {
teams.set(team.TeamId, team);
team.players.forEach((player) => {
players.set(player.puuid, player);
});
});
});
}
})
})
return Response.json({ teams: [...teams.values()], players: [...players.values()] });
})
POST = async(request) => {
fetch initial data...
const players: Map<string, Player> = new Map();
const teams: Map<string, Team> = new Map();
await(async() => {
initialData.forEach((match) => {
validatematch()
if(matchisvalid){
match.stats.forEach((stat) => {
stat.stats.teams.forEach((team) => {
teams.set(team.TeamId, team);
team.players.forEach((player) => {
players.set(player.puuid, player);
});
});
});
}
})
})
return Response.json({ teams: [...teams.values()], players: [...players.values()] });
})
But on the response im only getting teams: Array(0) and same for players I know its something with the async context but cant figure out how to get it to behave as intended Ended up finding the solution, changed to a for await loop
Solution
Arctic
Arctic8mo ago
POST = async(request) => {
fetch initial data...
const players: Map<string, Player> = new Map();
const teams: Map<string, Team> = new Map();
for await (const match of initialdata){
validatematch()
if(matchisvalid){
match.stats.forEach((stat) => {
stat.stats.teams.forEach((team) => {
teams.set(team.TeamId, team);
team.players.forEach((player) => {
players.set(player.puuid, player);
});
});
});
}
}
return Response.json({ teams: [...teams.values()], players: [...players.values()] });
})
POST = async(request) => {
fetch initial data...
const players: Map<string, Player> = new Map();
const teams: Map<string, Team> = new Map();
for await (const match of initialdata){
validatematch()
if(matchisvalid){
match.stats.forEach((stat) => {
stat.stats.teams.forEach((team) => {
teams.set(team.TeamId, team);
team.players.forEach((player) => {
players.set(player.puuid, player);
});
});
});
}
}
return Response.json({ teams: [...teams.values()], players: [...players.values()] });
})