-1

I'm trying to wrtie an async function that will print a dad joke in the console when i click the button.

const btn = document.querySelector("button");
const getDadJoke = async () => {
    const config = { headers: { Accept: "application/json" } }
    res = await axios.get("https://icanhazdadjoke.com", config
    );
    return res.data.joke;
}

btn.addEventListener("click", () => {
    console.log(getDadJoke());
})

But It only prints out a promise in the console becasue I think async function always returns a promise object.

my question is How do I access the value returned from getDadJoke and console.log it.

I tried

const btn = document.querySelector("button");
let text = "orignal text"

const getDadJoke = async () => {
    const config = { headers: { Accept: "application/json" } }
    const res = await axios.get("https://icanhazdadjoke.com", config
    );
    text = res.data.joke;
}

btn.addEventListener("click", () => {
    console.log(text)
})

but it only prints out "original text". (because getdadjoke was nvr called lol)

3
  • await getDadJoke(); console.log( text ); - but you should return the joke from getDadJoke instead of mutating a global variable. Mutating shared state is bad.
    – Dai
    Commented Feb 10, 2023 at 5:11
  • 1
    You need to await the promise and then print it: btn.addEventListener("click", async () => console.log(await getDadJoke()))
    – Hao Wu
    Commented Feb 10, 2023 at 5:12
  • …or just print the joke from inside getDadJoke()
    – Bergi
    Commented Feb 10, 2023 at 7:00

1 Answer 1

0

Since your getDadJoke() is an async function, I will always return a Promise. You should use await or then() to get the value from Promise.

Using await

btn.addEventListener("click", async () => {
    console.log(await getDadJoke());
})

or Using then()

btn.addEventListener("click", () => {
    getDadJoke().then(joke => console.log(joke));
})

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.