Interesting Connundrum

I want to understand more clearly what is happening here? After calling the API through axios the console output provides me with:

“Promise { : “pending” }”

When I test inside the try with console.log then I get the object that I’m looking for but when I try to return it I get the above.

import axios from 'axios'

async function getResults(num) {
    
        try {
            const res = await axios("https://type.fit/api/quotes");
            return res.data[num]
        } catch (error) {
            alert(error)
        }
}



document.getElementById("new-quote").addEventListener("click", function(){
    // Generate Random Number between 0 and 1642
    let randomNum = Math.floor(Math.random() * 1642)
    let quoteObj = getResults(randomNum)
    console.log(quoteObj)

  });

The function returns a Promise, you have to either .then() it or make the callback async and use await.

document
  .getElementById("new-quote")
  .addEventListener("click", async function () {
    // Generate Random Number between 0 and 1642
    let randomNum = Math.floor(Math.random() * 1642);
    const quoteObj = await getResults(randomNum);
    console.log(quoteObj);
  });
1 Like

Thank you for your helpful response.