I am currently struggling with calling a function that is defined inside an API Fetch response function. My code sends an API fetch request to the GitHub API to retrieve a repository tree in JSON format. The problem arises when I try to call a function defined within the fetch outside of it, as it seems to be encapsulated within the fetch function.
Despite my efforts to find a solution online and by reaching out for help, I have not been able to resolve this issue. As someone new to JavaScript, I acknowledge that my code may not be well-organized.
Here is a portion of the code causing the problem:
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)
})
Trying to call DELTA_location("")
from outside the fetch block results in an error like this:
fetch(api_TreeURL)
"...the code..."
})
DELTA_location("test")
The error message reads:
Uncaught ReferenceError: DELTA_fetch is not defined
. This error also occurs when attempting to call it from an HTML button.
If you wish to see the entire code, you can visit the GitHub page.