Hello,
Here is my solution to a code challenge.
I can see it’s working. I thought I was almost done when I saw the console.log was what I expected. The only step left was making the getNumDraws function to actually return numOfDrawnMatchesInYear. Oh boy…
Note: the exercise gives the function with the async keyword (commented out). I don’t even know if I could delete it regarding that it was given from the beginning. So if possible, consider that async keyword exists and can’t be removed.
Maybe that hides a hint to the solution I can’t figure out.
I thought Promise.all() would give me the keys to the async heaven after reading this article:
Would you have used another approach? How would you get the getNumDraws function return the value that it shows in the console.log?
Any help or feedback will be more than welcome. Thanks in advance!
PS: Not too satisfied with declaring loadMultipleDrawRequests and invoking it right away. Does it look right to you?
CODE UPDATED AFTER SOME FEEDBACK, READ COMMENT BELOW TO SEE THE OUTPUT
async function getNumDraws(year) {
function fetchData(numGoals) {
return new Promise((resolve, reject) => {
fetch(
`https://jsonmock.hackerrank.com/api/football_matches?year=${year}&team1goals=${numGoals}&team2goals=${numGoals}&page=1`
)
.then((res) => res.json())
.then((data) => resolve(data.total))
.catch((err) => console.log(err));
});
}
function loadMultipleDrawRequests() {
const possibleNumOfGoalsScoredByTeam = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const numOfDrawRequests = [];
possibleNumOfGoalsScoredByTeam.forEach((goalsByTeam) => {
numOfDrawRequests.push(fetchData(goalsByTeam));
});
return Promise.all(numOfDrawRequests).then((allDrawData) => {
const numOfDrawnMatchesInYear = allDrawData.reduce(
(acc, currVal) => acc + currVal
);
return numOfDrawnMatchesInYear;
});
}
let innerFunctionReturnVal = await loadMultipleDrawRequests();
console.log("value displayed:", innerFunctionReturnVal);
return innerFunctionReturnVal; // **I want to return an int (value displayed), NOT a promise**
}
getNumDraws(2011);