How to use fetch with async/await?

隐身守侯 提交于 2020-04-16 06:12:18

问题


I start by saying that I am not 100% sure this is the problem, I mean using await and async.

This is the scenario:

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...
      });
    }

But then I need to be able to click a button and re run that function with the 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())

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.


回答1:


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.

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? [duplicate]

2 - Fetch API Using Async/Await Return Value Unexpected [duplicate]



来源:https://stackoverflow.com/questions/54950838/how-to-use-fetch-with-async-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!