I am new to asynchronous functions, and I am trying to dynamically create an unordered list (ul) containing list items (li) with a child span element in each li. The span contains information coming from a mongo db. I want the for loop to wait for the results in each iteration before continuing. How do I modify this to accommodate the asynchronous operation of fetch?
Thanks in advance.
$('.add').on("input", function() {
var table = document.getElementById("table").getElementsByTagName('tbody')[0];
//Input text
var searchInput = this.value;
var searched_ul = document.getElementById('searched_ul');
fetch("______",{
}).then(response => {
return response.json();
}).then(data => {
for(var i=0; i<data.length; i++){
if(capitalizeFirstLetter(data[i].name).startsWith(capitalizeFirstLetter(searchInput)) && searchInput != ''){
var searched_li = document.createElement('li');
searched_li.innerHTML = data[i].name;
//Outputs all the names from the for loop as expected, but fetch only does last item
console.log("NAME", data[i].name);
//Span child element containing info
var dep_span = document.createElement('span');
//Add css class for styling
dep_span.classList.add('dep-span');
fetch("_______" + data[i].d,{
}).then(response => {
return response.json();
}).then(depData => {
dep_span.innerHTML = depData.name;
//Outputs li and span for last item in for loop (i times)
console.log("LI: ", searched_li);
//Append span to li
searched_li.appendChild(dep_span);
});
searched_li.addEventListener("click", function(e){
});
searched_ul.append(searched_li);
}
}
}).catch(function(err){
console.log(err);
});
});