简体   繁体   English

运行在 Promise.then() 中定义的函数

[英]Run a function defined inside a Promise.then()

I have a function to read a file which returns a Promise :我有一个函数来读取一个返回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() :然后,我仅在使用.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:但是当我尝试使用 HTML 页面上的按钮调用myFunction

<button id ="myButton1" onclick="myFunction()">The do stuff button</button>

I'm facing this error: Uncaught TypeError: myFunction is not a function我正面临这个错误: 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 promise.then 函数仅在内部定义时才有效
Calling a function that's defined inside a function 调用在函数内部定义的函数
How does Promise run when .then method is not called? 当 .then 方法没有被调用时,Promise 是如何运行的?
Javascript call nested function Javascript调用嵌套函数

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:由于您仅在fetchFile解析后定义myFunction ,因此fetchFile使用addEventListener向按钮添加一个侦听器,并删除内联处理程序:

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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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