Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 296
rob.m Avatar asked Mar 01 '19 19:03

rob.m


People also ask

How do you use async await for Fetch?

Using async/awaitYou start by specifying the caller function as async and then use await to handle the promise. Because of the await keyword, the asynchronous function pauses until the promise is resolved. The Response object is assigned to response once the request completes.

Does fetch support async await?

Because fetch() returns a promise, you can simplify the code by using the async/await syntax: response = await fetch() . You've found out how to use fetch() accompanied with async/await to fetch JSON data, handle fetching errors, cancel a request, perform parallel requests.

Is fetch synchronous or asynchronous?

forEach is synchronous, while fetch is asynchronous. While each element of the results array will be visited in order, forEach will return without the completion of fetch, thus leaving you empty-handed.

How do you wait for fetch to complete?

There are two ways to wait for fetch() : We can use then , and manipulate the response of our fetch() within then() . We can use await , and wait for the fetch to return before using its contents.


1 Answers

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]

like image 57
John Vandivier Avatar answered Sep 18 '22 17:09

John Vandivier