I have a function to read a file which returns a Promise:
const fetchFile = async () => {
let res = await fetch('myfile.json');
let feat = await res.json();
return fileContent;
}
Then, I run some code only when the promise has been resolved (i.e. when the actual file content has been loaded) using .then()
:
var external_variable = 2
fetchFile().then(fileContent => {
// do many things with fileContent and external_variable
const myFunction = (fileContent[0].properties) => {
// do stuff with some properties of the json object contained in the file
// which has been loaded and external_variable
}
// do other things
});
But when I try to call myFunction
using a button on my HTML page:
<button id ="myButton1" onclick="myFunction()">The do stuff button</button>
I'm facing this error: Uncaught TypeError: myFunction is not a function
Hence my question; how can I call this function when I click on my button?
These doesn't help much:
promise.then functions only works if defined inside
Calling a function that's defined inside a function
How does Promise run when .then method is not called?
Javascript call nested function