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.
.catch(console.error)
at the end offetch
? Is there any error that's caught? – Subinfeudatefetch(url).then(res => res.json())
and not at another part of your code? – Roomfetch
function with another function, becausefetch(url).then(res => res.json())
should never result in that error, iffetch
refers to the fetch API of the browser. But I would guess that the problem happens somewhere else. – Roomfetch
on window is being overridden by your code. Try this code in another browser or online sandbox.If it works...that's the case – Epicarpasync
andawait
added on there to get around being a duplicate... – Secondrate