ric*_*ava 4 javascript async-await arrow-functions fetch-api ecmascript-2017
我目前正在学习如何使用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));
Run Code Online (Sandbox Code Playgroud)
安慰:
"Chuck Norris can dereference NULL."
Run Code Online (Sandbox Code Playgroud)
但是我发现了一个使用箭头功能的片段,问题是我不知道如何在我当前的例子中按照我的方式返回我的值.
片段:
const fetchAsync = async () =>
await (await fetch(url)).json()
Run Code Online (Sandbox Code Playgroud)
如果这不是最佳做法让我知道,欢迎任何进一步阅读.
您可以再次使用与缩短常规相同的方法
async function tellJoke() {
let response = await fetch(url);
let data = await response.json();
return data.value.joke;
}
Run Code Online (Sandbox Code Playgroud)
你的实施.作为单行,它可以看起来像这样:
const tellJoke = async () => (await (await fetch(url)).json()).value.joke;
Run Code Online (Sandbox Code Playgroud)