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)
await getDadJoke(); console.log( text );
- but you should return thejoke
fromgetDadJoke
instead of mutating a global variable. Mutating shared state is bad.await
the promise and then print it:btn.addEventListener("click", async () => console.log(await getDadJoke()))
getDadJoke()