简体   繁体   English

如何使用async / await获取?

[英]How to use fetch with async/await?

I start by saying that I am not 100% sure this is the problem, I mean using await and async. 我首先说我不是100%确定这是问题,我的意思是使用await和async。

This is the scenario: 这是场景:

I run this when I first load the page, and works fine, I get the data : 我在第一次加载页面时运行它,并且工作正常,我得到了data

    externalContent(url);

    function externalContent(url) {
      fetch(url)
      .then(res => res.json())
      .then(data => {
        ...cool data...
      });
    }

But then I need to be able to click a button and re run that function with the fetch 但是我需要能够单击一个按钮并使用fetch重新运行该功能

So I do 所以我这样做

    $(".alm-filters--button").on("click", function() {
      externalContent(url);
    }); 

But when I click, It gives me an error on .then(res => res.json()) 但是当我点击它时,它会给我一个错误.then(res => res.json())

The error says: Uncaught (in promise) TypeError: Cannot read property 'then' of undefined 错误说: Uncaught(在promise中)TypeError:无法读取未定义的属性'then'

I believe there is an asynchronous issue, I tried, but I do not know enough about using async and await, yet I tried: 我相信有一个异步问题,我试过,但我不太了解使用async和await,但我尝试过:

    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 substitutes for .then() , so when using await fetch , you don't need to use .then() at all. await替换.then() ,所以当使用await fetch ,你根本不需要使用.then()

Here are a couple other answers which deal with more or less the same issue: 以下是其他一些处理或多或少相同问题的答案:

1 - How can I acces the values of my async fetch function? 1 - 如何访问异步获取功能的值? [duplicate] [重复]

2 - Fetch API Using Async/Await Return Value Unexpected [duplicate] 2 - 使用Async / Await获取API返回值意外[重复]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM