Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES8 using arrow function with async and await

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.

like image 593
ricardoNava Avatar asked Jan 29 '23 17:01

ricardoNava


2 Answers

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;
like image 78
Bergi Avatar answered Feb 01 '23 06:02

Bergi


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;
}
like image 43
Suren Srapyan Avatar answered Feb 01 '23 08:02

Suren Srapyan