[英]How to call a function inside a function from outside of it?
我有一个执行获取和处理这些数据的函数:
async function fetchData(){
const res = await fetch("./data.json");
const data = await res.json();
// processing one-time code
function doSome() {
// code that looks for something in data and processes it(I'm going to call this function many times)
}
doSome()
}
fetchData();
我可以在 fetchData 内部调用 doSome 函数,但我需要在 fetchData 外部调用 doSome。
如何不处理一次性代码而只运行 doSome?
function doSome(data) {
// code that looks for something in data and processes it(I'm going to call this function many times)
}
async function fetchData(){
const res = await fetch("./data.json");
const data = await res.json();
// processing one-time code
return data;
}
let data;
fetchData().then(fetchResult => {
//Stuff you want to do once you have the data.
data = fetchResult;
doSome(data);
// Handle any queued events.
});
// Pseudo-code event handler you can attach before data is ready
const eventHandler = (event) => {
if (!data) {
// Pseudo-code denoting a function that queues an event to be executed later
queueEvent(event)
} else {
doSome(data)
}
}
所以我从 fetchData 的范围中删除了 doSome 到模块的范围中。 然后我更改了 fetchData 以返回数据,以便我们稍后可以使用该结果。 一旦它解决了,它就会设置变量data
,您可以重新使用它,并在then
回调中执行任何所需的操作。 根据您的需要,您可以在那里添加事件侦听器,也可以将事件排队并在数据解析后触发需要数据的处理程序。 希望这可以帮助!
内部函数作用域仅限于外部函数。 因此它不能从外部调用,类似于从函数内部声明的变量。
似乎您有两个独立的操作,其中一个的输出是另一个的输入。 因此,执行两个单独的函数,您将获得更清晰的代码。
async function fetchData(){
const res = await fetch("./data.json");
const data = await res.json();
return data;
}
const json = fetchData();
function doSome(json) {
// code that looks for something in data and processes it(I'm going to call this
function many times)
}
doSome(json);
doSome(json);
doSome(json);
doSome(json);
如果您想将它们一起发送,您始终可以将它们封装在 JSON/Object 中。 尝试导出正确的方法并保留一个全局(到此文件)变量来保存 JSON。
let json = {};
async function fetchData(){
const res = await fetch("./data.json");
const data = await res.json();
json = data;
}
function doSome() {
console.log(json);
// code that looks for something in data and processes it(I'm going to call this
function many times)
}
//You probably want to call this from the outside, not in this file.
doSome();
doSome();
fetchData();
doSome();
doSome();
//not sure what is your functionality, so not sure what you would need to export here
export default {
fetchData,
doSome
}
使 doSome 成为一个闭包并从方法中返回它。
async function fetchData() {
// do your fetch logic
const doSome = () => {
// logic
};
return doSome;
}
const doSome = await fetchData();
doSome();
闭包将确保您保留声明它的包装方法的正确上下文,确保它可以访问在 fetchData 方法上下文中声明的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.