4

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
ricardoNava
  • 685
  • 1
  • 7
  • 26

2 Answers2

5

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;
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Ok I understand now, by the way, i guess that doing `let data = await response.json().value.joke; return data;` Looks better than `let data = await response.json(); return data.value.joke;` Can I know your opinion about it? – ricardoNava Aug 23 '17 at 17:25
  • My personal opinion is not to introduce another variable only for returning it - `return` from a function named `tellJoke` is descriptive enough already. In any case, your first snippet doesn't work, you need parenthesis around the `await` expression. – Bergi Aug 23 '17 at 17:59
3

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;
}
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • 2
    `.json().value.joke` ... I think you need some () `(await (await fetch(url)).json()).value.joke;` – Jaromanda X Aug 23 '17 at 07:20
  • 2
    where I showed - I **think** ... I should probably check before speaking :p – Jaromanda X Aug 23 '17 at 07:22
  • 2
    yes, your code is wrong, because it will try to access `json().value.joke` ... but json() returns a promise, which doesn't have a `value` property, and it certainly wouldn't be the value of the json anyway – Jaromanda X Aug 23 '17 at 07:27