I am trying learn JavaScript and am making a version of the game 2048 for practice. My instructor has set up an api for us to save high scores to. I created a function to do this, as well as one to list the high scores. They work individually, but when I tried to call them under the same button, they do not work.
The function to get the scores is:
var GetHighScores = function () {
scoreList = [];
fetch("https://highscoreapi.herokuapp.com/scores").then(function (response) {
console.log("Scores received. Status:", response.status);
return response.json();
}).then(function(data){
//find the list
var list = document.querySelector("#highScores");
list.innerHTML="";
data.forEach(function (entry) {
//create a list item
var item = document.createElement("li");
//populate the list item
item.innerHTML = entry.name + ": " + entry.score;
//append te item to the list
list.appendChild(item);
scoreList.push(entry.score);
});
console.log(scoreList);
});
return scoreList;
};
And the combined function to pull in the high scores and post the users score (if it is in the top ten) is:
var submitScore = function () {
GetHighScores();
var leaderBoard = GetHighScores();
var threshold = parseInt(leaderBoard[0]);
console.log(leaderBoard);
if (score >= threshold) {
var initials = prompt("Enter Your Initials:");
fetch("https://highscoreapi.herokuapp.com/scores", {
method: "POST",
headers: new Headers({
"Content-type": "application/json"
}),
body: JSON.stringify({
name: initials,
score: score
})
}).then(function (response) {
console.log("Score submitted. Status: ", response.status);
console.log(score);
console.log(leaderBoard[9]);
});
} //end of if
};
Is there something simple that I am missing here?