-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)

zzh315
  • 1
  • 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 Feb 10 '23 at 05:11
  • 1
    You need to `await` the promise and then print it: `btn.addEventListener("click", async () => console.log(await getDadJoke()))` – Hao Wu Feb 10 '23 at 05:12
  • …or just print the joke from inside `getDadJoke()` – Bergi Feb 10 '23 at 07:00

1 Answers1

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));
})
BadPiggie
  • 5,471
  • 1
  • 14
  • 28