我有一个函数可以执行提取和处理这些数据:
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)
}
}
因此,我将doSome从fetchData的作用域中删除到模块的作用域。然后我更改了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方法上下文中声明的属性。