I'm currently having issues figuring out how to call a function that is defined inside an API Fetch responce function. I currently have an API fetch going out to the github API to get a repository tree. It comes back as a JSON file and my code does all of its stuff. The issue is that I have a function that is defined in the fetch (that I would like to call outside of the fetch, so I dont have to "re-fetch" each time), and I cant call it outside of the fetch (its sorta like a function inside a function).
I've looked around online and asked around and I cant seem to find any answers. I'm fairly new to JS (yes I know my code is messy).
Here is a snippet of my current code:
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)
})
If I try and call DELTA_location("")
from anywhere outside of the fetch, eg;
fetch(api_TreeURL)
"...the code..."
})
DELTA_location("test")
It will return the error: Uncaught ReferenceError: DELTA_fetch is not defined
Same if I call it from a button in the HTML file.
If you would like to view all of the code, vist the Github