如何在异步/等待中使用提取? [英] How to use fetch with async/await?
问题描述
我首先说我不是100%肯定这是问题所在,我的意思是使用await和async.
I start by saying that I am not 100% sure this is the problem, I mean using await and async.
这是场景:
我在第一次加载页面时运行此程序,并且运行正常,我得到了data
:
I run this when I first load the page, and works fine, I get the data
:
externalContent(url);
function externalContent(url) {
fetch(url)
.then(res => res.json())
.then(data => {
...cool data...
});
}
但是我需要能够单击一个按钮,然后使用fetch
But then I need to be able to click a button and re run that function with the fetch
我愿意
$(".alm-filters--button").on("click", function() {
externalContent(url);
});
但是当我单击时,它在.then(res => res.json())
But when I click, It gives me an error on .then(res => res.json())
错误说: 未捕获(承诺)TypeError:无法读取未定义的属性'then'
The error says: Uncaught (in promise) TypeError: Cannot read property 'then' of undefined
我尝试过存在异步问题,但是我对使用异步和等待知之甚少,但我尝试过:
I believe there is an asynchronous issue, I tried, but I do not know enough about using async and await, yet I tried:
async function externalContent(url) {
await fetch(url)
.then(res => res.json())
.then(data => {
...cool data...
});
}
但是等等,我遇到了同样的错误.
But et, I get the same error.
推荐答案
引用本文应该解决您的问题.也请参见代码段.
Referring to this article should take care of your issue. See the snippet as well.
async function exampleFetch() {
const response = await fetch('https://reqres.in/api/users/2');
const json = await response.json();
console.log(json);
}
exampleFetch()
await
替代.then()
,因此使用await fetch
时,您根本不需要使用.then()
.
await
substitutes for .then()
, so when using await fetch
, you don't need to use .then()
at all.
还有另外两个答案或多或少涉及同一问题:
Here are a couple other answers which deal with more or less the same issue:
2-使用Async/Await返回API来获取API的返回值意外]
这篇关于如何在异步/等待中使用提取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!