I want to call an arrow function that uses a fetch method which returns a value of the retrieved data. The problem is when I console.log the data from the fetch, it shows it correctly, but the return still returns an undefined object.
I tried using async await, also .then .catch but nothing seemed to work.
What should I do here?
let name = 'Abc';
let birthYear = "1994";
let randomResponse = [];
//init vars;
const APIcallsObject = {
"chuck-norris-joke": () => {
return fetch("https://api.chucknorris.io/jokes/random")
.catch(`Couldn't fetch data from kanye-quote API`)
.then(response => response.json())
.then(response => response.value)
.catch(`Couldn't retrieve such data from the API's responose`);
},
"kanye-quote": () => {
return fetch("https://api.chucknorris.io/jokes/random")
.catch(`Couldn't fetch data from kanye-quote API`)
.then(response => response.json())
.then(response => response.value)
.catch(`Couldn't retrieve such data from the API's responose`);
},
"name-sum": (name, birthYear) => {
let sum = 0;
for (let index = 0; index < name.length; index++)
sum += name.toLowerCase().charCodeAt(index) - 96;
return `sum = ${sum}`;
},
}
checkMatches(name, birthYear, randomResponse);
// get the random responose
let response = randomResponse[Math.floor(Math.random() * randomResponse.length)];
return res.status(200).send({"type" : response ,"result" : APIcallsObject[response](name, birthYear)});
randomResponse = []
const checkMatches = (name, birthYear, randomResponse) => {
if (birthYear <= 2000) randomResponse.push("chuck-norris-joke");
if (birthYear > 2000 && (name[0] != 'A' || name[0] != 'Z')) randomResponse.push("kanye-quote");
if (name[0] != 'Q') randomResponse.push("name-sum");
}