I need some guidance please.
Pure JS only, no jQuery please.
I'm assigning a fetch response to a variable at the top of the *.js file (multiple different fetch + vars, both GET and POST):
var srcDL;
fetch(url)
.then(response => response.json())
.then(data => srcDL = data);
This works ok, however later in the same file, I'm trying to iterate through the object, but the error is telling me srcDL is undefined.
Uncaught TypeError: Cannot read properties of undefined (reading 'length')...
I assume this is because the fetch is async, so the rest of the file is being executed before the fetch gets a successful response and has updated the variable.
Array.from(document.querySelectorAll('.AU_dList')).forEach(function(e){
var idx = e.getAttribute('data-idx');
var selitem = e.getAttribute('data-selitem');
var s = '';
var data = '';
for( var i = 0; i < srcDL.length; i++ ){
s = srcDL[i]['pk']==selitem ? ' selected' : '';
data = data + '<option value="' + srcDL[i]['pk'] + '" '+ s +'>' + srcDL[i]['name'] + '</option>';
}
document.getElementById("dept_"+idx).innerHTML = data;
});
I tried to wrapping the Array.from.... together with many other functions which depend of the fetch response to variable, into a delay with setTimeout(). This partially works, until another event needs to reference a function created inside of / after the setTimeout() has completed, resulting in another error:
<function> is not defined at HTMLSelectElement.onchange
Reading about async/await, this doesn't really solve my needs, because (if I understand it correctly), every instance of my DOM with class .AU_dList, will call the fetch url. Therefore calling the database several times in the same file getting the same response. Hence I want to initially make the call to DB, save the response under a variable, then use in within the file as many times as needed.
What is the best approach to have this working as expected? The fetch being ultra quick, or not being asynchronous? Am I nearly there or completely missed the point?
EDIT: Please re-open, this is not a duplicate.