As a beginner with Fetch API and Promises, I have encountered an issue that I hope someone can help me with.
My code involves fetching event data with a token, extracting team ids, and using these ids to fetch more information from another endpoint. Everything seems to be working fine until the last step where my variables are showing up as undefined.
Specifically, when running the code, I receive the error message:
"Reference Error: homeTeam is not defined"
I am also facing problems with "varStart" and "varEnd". Despite researching extensively, I'm unable to pinpoint the exact cause of the issue but I suspect it has something to do with promises hierarchy.
Below is a snippet of my code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var html = '<tr><td colspan=3 class=superBold> </td></tr>';
var params = {
grant_type: 'client_credentials',
client_id: 'xxxx',
client_secret: 'xxxx'
}
fetch('token_url', {
method: 'POST',
body: JSON.stringify(params),
headers: {
'Content-Type': 'application/json'
}
}).then(function(response){
return response.json()
}).then(function(token_data){
return fetch('event_url', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer' + ' ' + token_data.access_token,
}
}).then(function(event_response){
return event_response.json()
}).then(function(event_data){
var len = event_data.data.length
console.log(event_data)
for (var i = 0; i < len; i++){
var varStart = event_data.data[i].attributes.start.substr(11, 5);
var varEnd = event_data.data[i].attributes.end.substr(11, 5);
var hteam_id = event_data.data[i].attributes.hteam_id;
var vteam_id = event_data.data[i].attributes.vteam_id;
let a = fetch('team_url' + hteam_id, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer' + ' ' + token_data.access_token,
}
})
let b = fetch('team_url' + vteam_id, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer' + ' ' + token_data.access_token,
}
})
Promise.all([a,b])
.then(values => Promise.all(values.map(value => value.json())))
.then(function(team_data){
let homeTeamResp = team_data[0];
let awayTeamResp = team_data[1];
var homeTeam = homeTeamResp.data[0].attributes.name
let awayTeam = awayTeamResp.data[0].attributes.name
})
html += '<tr><td>' + i + '</td><td>' + 'HomeTeam: ' + homeTeam + ' AwayTeam: ' + awayTeam, + '</td><td>' + 'Start: ' + varStart + ' End: ' + varEnd + '</td></tr>';
}
$("#content").append(html);
})
})
</script>
</head>
<body>
<div id='content'> </div>
</body>
</html>