I'm currently learning how to use ES8's fetch, async and await I currently have this code that works:
const url = "";
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 weled.
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./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 weled.
Share Improve this question edited Oct 3, 2018 at 20:55 Felix Kling 817k181 gold badges1.1k silver badges1.2k bronze badges asked Aug 23, 2017 at 7:17 ricardoNavaricardoNava 7221 gold badge7 silver badges26 bronze badges 3- 2 The best practise is to only use arrow functions when you need them. Just go with your working code :-) – Bergi Commented Aug 23, 2017 at 7:24
-
2
Btw,
async
/await
is part of ES8 not ES7 – Bergi Commented Aug 23, 2017 at 7:26 - @Bergi that is true, forgot to check MDN and every example that I found mentioned ES7. – ricardoNava Commented Aug 23, 2017 at 17:22
2 Answers
Reset to default 5You 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;
}