Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

250
Vistas
Why does this sequence of await function calls run in the wrong order?

I want to output some text after 2 seconds first, after output some "alert()" second and at the end output some "console.log" by using only async/await. Please help me how to write such a sequence?

Why the code below does not work

async function qaz()
{
    let res1 = await setTimeout(function(){
        console.log("show me first");
    }, 2000);
    let res2 = await alert('show me second');
    let res3 = await console.log('show me at the end');
    return [res1,res2,res3];
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The setTimeout is part of the JavaScript asynchronous methods (methods that are starting to execute and their result will return sometime in the future to a component called the callback queue, later to be executed)

What you probably want to do is to wrap the setTimeout function within a Promise and await it and then execute the rest of the synchronous code.

const longTask = () => new Promise(resolve => {
      setTimeout(function(){
        console.log("show me first");
        resolve();
    }, 2000);
});
  
async function qaz()
{   
    await longTask();
    alert('show me second');
    console.log('show me at the end');
}

qaz();

I suggest to read more about the event loop model here

about 4 years ago · Juan Pablo Isaza Denunciar

0

Neither the setTimeout, the alert, or the console.log return promises, and that's a problem because await only works with promises.

You can still use async/await, however. Create a delay function that returns a promise you can await for the first part, and then after that resolves do your alerts and your logging.

function delay(n) {
  return new Promise(res => {
    setTimeout(() => res(), n);
  });
}

async function qaz() {
  await delay(2000);
  console.log('Show me first');
  alert('Show me second');
  console.log('Show me at the end');
}

qaz();

about 4 years ago · Juan Pablo Isaza 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 Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda