[英]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: 我目前正在学习如何使用ES8的fetch,async等待我现在有这个代码可以工作:
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. 如果这不是最佳做法让我知道,欢迎任何进一步阅读。
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. 如果你的代码中没有正文表达式(witout
{}
),它将返回语句的结果。 In this case the result of await (await fetch(url)).json().value.joke
. 在这种情况下,
await (await fetch(url)).json().value.joke
的结果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. 使用body expression
{}
您需要在简单函数中显式返回。
const fetchAsync = async () => {
const result = await fetch(url);
const data = await result.json();
return data.value.joke;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.