【问题标题】:Run a function defined inside a Promise.then()运行在 Promise.then() 中定义的函数
【发布时间】:2021-01-21 17:52:45
【问题描述】:

我有一个函数可以读取一个返回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 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

【问题讨论】:

标签: javascript function button nested


【解决方案1】:

内联处理程序may only reference global variables(无论如何都不应该在现代代码中使用,它们有太多问题无法使用)。

由于您只在 fetchFile 解析后定义 myFunction,因此在此时为带有 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
});

【讨论】:

  • 可能还在默认情况下(在承诺履行之前)添加一个事件监听器,提醒“文件仍在加载,再试一次”,并在 catch 中添加另一个事件监听器,提醒错误消息,这样按钮在点击过早或失败时不会失效。
猜你喜欢
  • 1970-01-01
  • 2022-07-12
  • 1970-01-01
  • 1970-01-01
  • 2011-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多