首页 > 解决方案 > 运行在 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
});

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

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

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

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

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

标签: javascriptfunctionbuttonnested

解决方案


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

由于您仅myFunctionfetchFile解析后定义,因此在此时向按钮添加一个侦听器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
});

推荐阅读