Javascript-Async/Await+。然后
你能帮我确认几个问题吗。下面的第一个代码是使用标准承诺处理异步数据:Javascript-Async/Await+。然后,javascript,async-await,Javascript,Async Await,你能帮我确认几个问题吗。下面的第一个代码是使用标准承诺处理异步数据: export const fetchData = () => { try { // const response = await fetch(url) fetch(url) .then(res => res.json()) .then(data => console.log(data)); } catch (error) { console.log(er
export const fetchData = () => {
try {
// const response = await fetch(url)
fetch(url)
.then(res => res.json())
.then(data => console.log(data));
} catch (error) {
console.log(error.message);
}
}
下面的代码使用了使用async/await的ES7方法:
export const fetchData = async () => {
try {
const response = await fetch(url)
const data = await response.json();
console.log(data);
} catch (error) {
console.log(error.message);
}
}
现在,我看到了这两个方面的变化,如下所示。您能否确认这是否只是有人可能有点困惑,或者是否有真正的理由将两者混合在一起(async/await+。then)。虽然它工作正常,但人们应该坚持一种方法,不是吗
export const fetchData = async () => {
try {
const response = await fetch(url)
.then(response => response.json())
.then(data => console.log(data));
} catch (error) {
console.log(error.message);
}
}
最后一段代码显然是错误的,因为console.log不会返回任何东西。如果您是对的,应该坚持使用一种方法。我确实认为最下面的一个假设实际上是相同的,但我不建议这样做,因为您最好还是坚持
async/await
,而不要在async中使用这样的承诺function@DownloadPizza我想他们都不会返回任何东西,因为“url”是空的。@downloadppizza我不认为这是“错的”。据我所知,它将表现为sameYes,但将值绑定到const response
意味着打算使用json