Home > other >  How do I call my dialog before multiple async/await starts and close after those calls are completed
How do I call my dialog before multiple async/await starts and close after those calls are completed

Time:12-04

I want call my dialog box before the sequence of multiple async/await calls. This is my code:

document.getElementById("dialog").showModal();

if(condition 1 is true){
    if(condition 2 is true){
        (async()=>{
             await f1();
        })();
    }
}

if(condition 3 is true){
    if(condition 4 is true){
        (async()=>{
             await f2();
        })();
    }
}

if(condition 5 is true){
    if(condition 6 is true){
        (async()=>{
             await f3();
        })();
    }
}

document.getElementById("dialog").close();

Upon executing the code, the dialog opens and closes instantly before the async/await calls even complete. How do I close the dialog only when all the server calls are completed?

CodePudding user response:

The only code that will wait for the promise to resolve is other code in the same async function, after the await. Code outside the async function will not wait. So your tiny async functions do next to nothing, because there is no code after their awaits.

You need to write this code as one large async function.

const someFunction = async () => {
  document.getElementById("dialog").showModal();

  if(condition 1 is true){
    if(condition 2 is true){
      await f1();
    }
  }

  if(condition 3 is true){
    if(condition 4 is true){
      await f2();
    }
  }

  if(condition 5 is true){
    if(condition 6 is true){
      await f3();
    }
  }

  document.getElementById("dialog").close();
}
  • Related