I have this function which takes a few seconds to complete, and I need to wait for it to complete before anything else can happen in my application. I tried implementing an async function which returns a promise but still, the function load_structure is being executed before any other functions in the load_question(). I need them to execute in the order they appear (or at least, the load_structure needs to be called before the two succeeding functions can be executed).
My code looks like this
function show_loading() { // All of the show/hide functions work on this principle
document.getElementById('loading').removeAttribute("hidden");
}
async function generate_html_a(){ // Same for B and C just different logic
// Spends a few seconds rendering some HTML objects
}
async function load_structure(){
if(a){
await generate_html_a(); // renders a bunch of images which takes a few seconds
}else if(b){
await generate_html_b();
}else if(c){
await generate_html_c();
}
}
async function load_question(){
hide_question();
show_loading();
await load_structure();
hide_loading();
show_question();
}
Edit: I think I have boiled it down to a reprex.
function show_loading() {
document.getElementById('loading').removeAttribute("hidden");
}
function hide_loading() {
document.getElementById('loading').setAttribute("hidden", "");
}
async function load_html_a() {
document.getElementById("question").innerHTML = '';
for (i = 0; i < 100000; i++) {
var container = document.createElement('div');
container.innerHTML = 'aaaaaaa';
//container.setAttribute("hidden", "");
document.getElementById("question").appendChild(container);
}
//document.getElementById("question").innerHTML = '';
return;
}
async function load_structure() {
if (1 == 1) {
await load_html_a();
}
return;
}
async function load_question() {
console.log("start");
show_loading();
await load_structure();
hide_loading();
console.log("done");
}
<div id='loading' hidden>loading</div>
<button onClick='load_question()'>Load</button>
<div id='question'></div>