javascript - 运行在 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调用嵌套函数
解决方案
内联处理程序只能引用全局变量(无论如何都不应该在现代代码中使用,它们有太多问题无法使用)。
由于您仅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
});
推荐阅读
- javascript - 我正在尝试使用覆盖打开侧面板并关闭
- css - 根据列中的内容自动行
- python - Pandas 在导入 SQLite 数据库时创建关系?
- javascript - 相互堆叠的 HTML 图像未在网格中显示
- java - SaxBuilder 或 jaxb 中的 XML 模式验证?
- powerbi - 在 Power BI 中形成动态度量
- reactjs - 使用 Reactjs 将后端链接到前端
- python - 在 visuaæ studio 中导入图标
- amazon-web-services - Vaadin 不能在没有粘性会话的情况下在云中使用?
- google-apps-script - 我想从包含多行的 Google 电子表格中的数据创建一个文档