• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

62
Vistas
Can I safely call an asynchronous function at the end of a synchronous function?

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 onload
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.

almost 3 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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
almost 3 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda