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.
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.
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With