Home > Back-end >  Can I safely call an asynchronous function at the end of a synchronous function?
Can I safely call an asynchronous function at the end of a synchronous function?

Time:12-27

I can't seem to find a straightforward answer to this one, as almost every resource inverts my question to "Can I call synchronous from within Asynchronous". I'm also asking out of curiosity and with the intention of understanding the relationship between sync and async.

Below is a very basic example of what I was thinking, but I've previously worked with some asynchronous and synchronous elements poorly in the past and want to follow a best practice.

These are all functions I know can safely run first, as most of them are html setups based on a few system details such as date and time.


// Fires from body's onl oad
function startup(){
   // Begin startup and setup
   makeDivs();
   getDate();
   setUpInputHandlers();
   
   
   // Begin API and Async functions
   startupAsync();
}

async function startupAsync(){
   await callApi();
   await doDataWork();
   // more async functions throughout.
}

I'm not looking to do anything synchronous with the async data, but I want a few processes to run before I jump onto my API calls and work with API data. Would something akin to the above be a safe way to do this? I know it would be easier to make both startups async.

CodePudding user response:

If you want startup() to execute the async functions callApi() and doDataWork() before doing something else, then startup should be an async function too.

async function startup(){
   makeDivs();
   getDate();
   setUpInputHandlers();
   await callApi();
   await doDataWork();
}

await startup()
// then do something afer the async functions finish

If you want to do something else while the async functions run, then startup does not need to be an async function.

function startup(){
   makeDivs();
   getDate();
   setUpInputHandlers();
   (async function(){
     await callApi();
     await doDataWork();
   })();
}

startup()
// do something while async operations run
  • Related