I am writing a web application showing departures from a preselected station. An id of the selected station is saved as a coockie. A JSON file containing id's and full names is read into an array with the id's as keys and full names as values, like this Stations[Id] = FullName. This works just fine when writing to console but not to the html page when it is opened or reloaded, the checkCoockie()function. It says undefined instead of the station. After a new station has been chosen the stations full name is shown properly, the setCoockie()function.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
var Stations = [];
function onLoad() {
checkCookie();
return;
}
async function loadStations() {
fetch("tinystations.json")
.then(response => response.json())
.then(stations => stations.forEach(item =>
Stations[item.Id] = item.FullName));
return;
}
async function checkCookie() {
await loadStations();
console.log(Stations);
var station1 = getCookie("station1");
document.getElementById("chosen1").innerHTML = station1 + " : " + Stations[station1];
return;
}
function setCookie() {
const d = new Date();
d.setTime(d.getTime() + 100000000000); // Sufficiant amount of time. 3 years.
let expires = "expires=" + d.toUTCString();
let station1 = document.getElementById("TIstation1").value;
document.cookie = "station1=" + station1 + ";" + expires;
document.getElementById("chosen1").innerHTML = station1 + " : " + Stations[station1];
return;
}
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
</script>
</head>
<body onload="onLoad()">
<div id="coockie">
<p>Select new stations</p>
<input id="TIstation1" type="text" placeholder="Choose station" />
<button onclick="setCookie()">Save</button>
</div>
<div id="chosen">
Preselected:
<p id="chosen1"> </p>
</div>
</body>
</html>
This is my JSON file:
[
{
"FullName": "Arlanda C",
"Id": "Arnc"
},
{
"FullName": "Huddinge",
"Id": "Hu"
},
{
"FullName": "Jakobsberg",
"Id": "Jkb"
},
{
"FullName": "Stuvsta",
"Id": "Stu"
},
{
"FullName": "Rotebro",
"Id": "R"
},
{
"FullName": "Stockholm City",
"Id": "Sci"
}
]
When opening or reloading page it look like this:

And after a new station been chosen and new coockie set:

I thought the Stationsarray might not be ready when checkCoockie() was executed so I made checkCoockie() async and made it wait for loadStations() to finish. That didn't help. I have tried many async/await solutions the last month but none have helped.
Any suggestions how I can get this to work on page load?
loadStationsdoesn't need to beasyncsince you're not awaiting anything. Technically you just need toreturn fetch()and things should work... I'd suggest though that you remove the globalStationsvariable and instead return a new stations object form your.then()and then useconst stations = await loadStations()when callingloadStations.Stationsas a function value has crossed my mind but I rather not go that way. I don't see how I can useStationsin thesetCoockiefunction. That function is called when I push a button. And I'd prefer not to read the JSON file again. It is not huge but still around 50kb. Another reason is that I set another array in theloadStations, not shown in this example because it's working and I wanted to cut out all that's not relevant. I have to give up on this. It's annoying me though, that I can't figure out why it's not working.