ES8 using arrow function with asynchronous and wait

I am currently learning how to use ES8 fetch, async and expect that I 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 the arrow function, the problem is that I don’t know how to return the value, as I do in my current example.

SNIPPET:

const fetchAsync = async () => 
await (await fetch(url)).json()

If this is not best practice, let me know, any further reading is also welcome.

+4
source share
2 answers

You can again use the same approach that was used to reduce the usual

async function tellJoke() {
  let response = await fetch(url);
  let data = await response.json();
  return data.value.joke;
}

to your implementation. How single line it might look like this:

const tellJoke = async () => (await (await fetch(url)).json()).value.joke;
+5
source

. (witout {}), . await (await fetch(url)).json().value.joke.

const fetchAsync = async () => (await (await fetch(url)).json()).value.joke;

. {} .

const fetchAsync = async () => {
   const result = await fetch(url);
   const data = await result.json();
   return data.value.joke;
}
+3

Source: https://habr.com/ru/post/1684277/


All Articles