javascript - 从 fetch 之外的其他地方调用在 fetch 中定义的函数
问题描述
我目前在弄清楚如何调用在 API Fetch 响应函数中定义的函数时遇到问题。我目前有一个 API 提取到 github API 以获取存储库树。它以 JSON 文件的形式返回,我的代码完成了所有工作。问题是我有一个在 fetch 中定义的函数(我想在 fetch 之外调用,所以我不必每次都“重新获取”),我不能在 fetch 之外调用它(它有点像函数内部的函数)。
我在网上四处寻找并四处询问,我似乎找不到任何答案。我对 JS 很陌生(是的,我知道我的代码很乱)。
这是我当前代码的片段:
fetch(api_TreeURL)
.then(function(response) {
return response.json()
}).then(function(json) {
function GetSortOrder(prop) {
return function(a, b) {
if (a[prop] > b[prop]) {
return 1;
} else if (a[prop] < b[prop]) {
return -1;
}
return 0;
}
}
function DELTA_location(currrentlLocation) {
var parentlocation = document.getElementById("delta");
var dirLocation = document.createElement("div")
var dirLocationText = document.createElementNS("http://www.w3.org/1999/xhtml","a")
var lastChar = currrentlLocation.substr(-1);
parentlocation.append(dirLocation)
dirLocation.append(dirLocationText)
dirLocation.setAttribute("class","delta-location")
if (lastChar != '/') {
currrentlLocation = currrentlLocation + '/';
}
dirLocationText.innerHTML = currrentlLocation
}
}).catch(function(ex) {
console.log('parsing failed', ex)
})
如果我尝试DELTA_location("")
从 fetch 之外的任何地方打电话,例如;
fetch(api_TreeURL)
"...the code..."
})
DELTA_location("test")
它将返回错误:Uncaught ReferenceError: DELTA_fetch is not defined
如果我从 HTML 文件中的按钮调用它,则相同。
如果您想查看所有代码,请访问Github
解决方案
您可以做的是使用对该函数的引用,例如:在您编写的获取代码之外
let DELTA_location_ref = (a) => console.warn('Function not fetched yet');
然后在获取代码中,您将此变量覆盖为:
DELTA_location_ref = (currrentlLocation) => {
var parentlocation = document.getElementById("delta");
var dirLocation = document.createElement("div")
var dirLocationText = document.createElementNS("http://www.w3.org/1999/xhtml","a")
var lastChar = currrentlLocation.substr(-1);
parentlocation.append(dirLocation)
dirLocation.append(dirLocationText)
dirLocation.setAttribute("class","delta-location")
if (lastChar != '/') {
currrentlLocation = currrentlLocation + '/';
}
dirLocationText.innerHTML = currrentlLocation
}
在这里使用闭包(箭头函数)很重要,因为您希望在从外部调用时访问 fetch 的上下文
请注意,您的 delta 位置函数不使用 fetch(json 变量)的返回,所以我不知道您为什么在那里定义它
推荐阅读
- c++ - 非零 降低成本:下限或上限是否有效?
- ios - 使用 UIGestureDetector 检测用户与视图的交互
- reactjs - 如何使用 Firebase 的 GUI 从 Firebase 存储中获取图像?
- sql - 在 postgres 中提取独特的结果并降低星型模式的成本
- c++ - 几个按钮的 fltk 回调函数
- linux - 无法在已安装的 Azure 文件共享中删除 K8s 容器内的文件
- flutter - Flutter 从另一个类调用 RFlutter Alert
- docker - Traefik:负载平衡内部服务而不将其暴露在外部
- docusignapi - DocuSign:如何以编程方式获取授权码
- file - Vue 推送事件文件到输入文件