繁体   English   中英

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

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

我有一个函数来读取一个返回Promise的文件:

const fetchFile = async () => {
    let res = await fetch('myfile.json');
    let feat = await res.json();
    return fileContent;
}

然后,我仅在使用.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
});

但是当我尝试使用 HTML 页面上的按钮调用myFunction

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

我正面临这个错误: Uncaught TypeError: myFunction is not a function

因此我的问题; 单击按钮时如何调用此函数?

这些没有多大帮助:
promise.then 函数仅在内部定义时才有效
调用在函数内部定义的函数
当 .then 方法没有被调用时,Promise 是如何运行的?
Javascript调用嵌套函数

内联处理程序可能只引用全局变量(无论如何都不应该在现代代码中使用,它们有太多问题无法使用)。

由于您仅在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