最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ES8 using arrow function with async and await - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 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;

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;
}
发布评论

评论列表(0)

  1. 暂无评论