简体   繁体   中英

Run a function defined inside a Promise.then()

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 (ie 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

Inline handlers may only reference global variables (and should never be used in modern code anyway, they have way too many problems to be used anyway).

Since you only define myFunction after the fetchFile resolves, add a listener to the button with addEventListener at that point, and remove the inline handler:

var external_variable = 2
fetchFile().then(fileContent => { 
    // do many things with fileContent and external_variable
    const myFunction = () => {
        // do stuff with some properties of the json object contained in the file
        // which has been loaded and external_variable
    };
    document.querySelector('#myButton1').addEventListener('click', myFunction);
    // do other things
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM