Is it possible to wait until the Javascript Fetch API to complete before executing the next code/instruction??
I want to wait for the response coming from the fetch. And then start executing the code further
function toggle(){
console.log("hello 1");
fetch('url')
.then(response => response.json())
.then(data => {
console.log("hello 2");
data.forEach(user => {
let li = document.createElement("LI");
let typ = document.createAttribute("class");
typ.value = "list-group-item";
li.attributes.setNamedItem(typ);
li.innerHTML = `${user.username}`
ul.appendChild(li);
console.log("hello 3");
})
})
.catch(err => console.log(err.message()))
let txtValue;
filter = input.toUpperCase();
let li = document.getElementsByTagName("LI");
console.log("hello 4");
for(let i = 0 ; i < li.length ; i++){
txtValue = li[i].textContent || li[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) === 0) {
li[i].style.display = "block";
} else {
li[i].style.display = "none";
}
}
console.log("hello 5");
document.body.appendChild(ul);
}
I expect the output on the console to be
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
but the actual output on console is
Hello 1
Hello 4
Hello 5
Hello 2
Hello 3