我有一个执行提取并处理此数据的功能:
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?
答案 0 :(得分:1)
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
回调中执行所有必需的操作。根据您的需求,您可以在其中添加事件侦听器,也可以将事件排队并在解析后触发需要数据的处理程序。希望这会有所帮助!
答案 1 :(得分:0)
内部功能范围仅限于外部功能。因此,不能像从函数内部声明的那样从外部调用它。
答案 2 :(得分:0)
似乎您有两个独立的动作,其中一个的输出是另一个的输入。因此,执行两个单独的功能,您将获得更简洁的代码。
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
}
答案 3 :(得分:0)
使doSome闭合并从方法中返回它。
async function fetchData() {
// do your fetch logic
const doSome = () => {
// logic
};
return doSome;
}
const doSome = await fetchData();
doSome();
闭包将确保您保留在其中声明的包装方法的正确上下文,以确保它可以访问在fetchData方法上下文中声明的属性。