rob*_*b.m 10 javascript async-await ecmascript-6
我首先说我不是 100% 确定这是问题所在,我的意思是使用 await 和 async。
这是场景:
我在第一次加载页面时运行它,并且工作正常,我得到data:
externalContent(url);
function externalContent(url) {
fetch(url)
.then(res => res.json())
.then(data => {
...cool data...
});
}
Run Code Online (Sandbox Code Playgroud)
但随后我需要能够单击一个按钮并重新运行该功能 fetch
所以我做
$(".alm-filters--button").on("click", function() {
externalContent(url);
});
Run Code Online (Sandbox Code Playgroud)
但是当我点击时,它给了我一个错误 .then(res => res.json())
错误说:未捕获(承诺)类型错误:无法读取未定义的属性“then”
我相信有一个异步问题,我试过了,但我对使用 async 和 await 还不够了解,但我试过:
async function externalContent(url) {
await fetch(url)
.then(res => res.json())
.then(data => {
...cool data...
});
}
Run Code Online (Sandbox Code Playgroud)
但是,我得到了同样的错误。
Joh*_*ier 23
参考这篇文章应该可以解决您的问题。另请参阅代码段。
async function exampleFetch() {
const response = await fetch('https://reqres.in/api/users/2');
const json = await response.json();
console.log(json);
}
exampleFetch()Run Code Online (Sandbox Code Playgroud)
await代替.then(),因此在使用时await fetch,您根本不需要使用.then()。
以下是其他一些或多或少涉及相同问题的答案:
| 归档时间: |
|
| 查看次数: |
8233 次 |
| 最近记录: |