0

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");
}
  • I faced same problem and couldn't find a good solution, what I did was made a global variable and appended to it whatever results I wanted and then used that variable. Since I used await, I always got result in desired order. – Wilfred Almeida Aug 12 '21 at 16:53
  • It's not clear why this isn't a dupe of [How do I return the response from an aynchronous call](https://stackoverflow.com/q/14220321/438992), but I also find the code difficult to reason about, so I may be missing something. – Dave Newton Aug 12 '21 at 16:55
  • 1
    @DaveNewton As far as I'm concerned, it IS a dup of that. – Barmar Aug 12 '21 at 16:56

0 Answers0