I'm currently learning how to use ES8's fetch, async and await I currently have this code that works:
const url = "https://api.icndb.com/jokes/random";
async function tellJoke() {
let data = await (await fetch(url)).json();
return data.value.joke;
}
tellJoke().then(data => console.log(data));
Console:
"Chuck Norris can dereference NULL."
but I found a snippet using an arrow function, the problem is that I don't know how to return my value the way I'm doing it in my current example.
SNIPPET:
const fetchAsync = async () =>
await (await fetch(url)).json()
If this is not a best practice let me know, also any further reading is welcomed.
You can again use the same approach that you used to shorten the usual
async function tellJoke() {
let response = await fetch(url);
let data = await response.json();
return data.value.joke;
}
to your implementation. As a one-liner it can look like this:
const tellJoke = async () => (await (await fetch(url)).json()).value.joke;
Use as same in the function. If you have no body expression in your code (witout {}
), it will return the result of the statement. In this case the result of await (await fetch(url)).json().value.joke
.
const fetchAsync = async () => (await (await fetch(url)).json()).value.joke;
or with multi line body. With body expression {}
you need explicitly return as in simple function.
const fetchAsync = async () => {
const result = await fetch(url);
const data = await result.json();
return data.value.joke;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With