【发布时间】:2021-05-31 12:02:34
【问题描述】:
我的代码适用于以下内容:
export async function FetchAPI(props){
const url = `www.website.com/${props}`
let res = await fetch(url)
let response = await res.json()
return response
}
但是当我尝试使用更好的做法清理代码时,我收到以下代码的错误,说它返回未定义。
export async function FetchAPI(props){
const url = `www.website.com/${props}`
fetch(url)
.then((resp => {
resp.json()
return resp
}))
}
任何人都了解其中的差异以及如何让第二个工作?
【问题讨论】:
-
你错过了
return fetch(url)...为了回报承诺。此外,您的第一个代码 sn-p 更清洁 IMO。另外,您没有正确使用resp.json()。你应该有return fetch(url).then(resp => resp.json())或return fetch(url).then(resp => { return resp.json() }) -
另外,
await在速度方面比then更好。你能解释一下then如何是一个“更好的实践”? -
@TheBombSquad 你有那个 speed 声明的参考。 AFAIK,
await只是完全相同过程的语法糖(参见stackoverflow.com/a/54497100/283366) -
@Phil 实际上我后来注意到 jfriend00 确实已经在他们的答案中链接到该帖子你确实链接到:) 而且他们的观点是表演不应该决定使用哪个仍然是正确的,性能方面的差异应该无关紧要,如果确实如此,那可能是因为代码设计中出现了其他问题。
-
@TheBombSquad 那是完全不同的代码。等效语法为
long.then(() => short)
标签: javascript reactjs api promise fetch