【发布时间】: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
【问题讨论】:
-
正如其他人所说,这是一个范围问题。你还有一个错字
myFnction -
已修复错字。感谢您指出这一点。
标签: javascript function button nested