[英]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.