I am working on a project that simulates generic sports matches. I am trying to add functionality where a user can upload/save teams to the project. To organize the scripts, I have separated various functions into different modules and am coordinating the overall functionality through main.js:
const uploadTeamButton = document.getElementById("upload-team-button");
uploadTeamButton.addEventListener("click", () => {
const loadTeamInput = document.getElementById("team-upload");
const upload = uploadTeamJSON(loadTeamInput).then(
() => {
console.log(upload);
allTeams = addTeam(upload, allTeams);
displayTeamsAtSelect(allTeams);
}
);
closeOverlay();
});
The function uploadTeamJSON() is defined in the module load-write-data.js:
export async function uploadTeamJSON(upload) {
const fr = new FileReader();
let newTeam = {};
let uploadJSON = {};
async function readFile() {
const data = fr.result;
console.log(data);
uploadJSON = JSON.parse(data);
console.log(uploadJSON.name + " uploaded.");
}
fr.readAsText(upload.files[0]);
fr.addEventListener("load", () => {
readFile().then(() => {
newTeam = newTeamInput(
uploadJSON.name,
uploadJSON.seed,
uploadJSON.streakType,
uploadJSON.streakLength,
);
console.log(newTeam);
return newTeam
});
});
}
This is the result in the console once the Upload button is clicked in the Web View:
{
"fileType": "team",
"simVersion": "1.2",
"name": "Test Team 1",
"seed": 5,
"streakType": "W",
"streakLength": 1
}
Test Team 1 uploaded.
Object {name: "Test Team 1", seed: 5, streakType: "W", streakLength: 1}
The issue I am having is that the code defined in .this() after uploadTeamJSON() in main.js appears to be running too early and is processing an undefined Object. The console.log doesn't even get executed. I am fairly new to JavaScript so I may be missing something, but shouldn't the code wait until uploadTeamJSON() is finished processing?
asyncfunctions but neverawaited anything in them. You just started reading the file and added an event listener.