Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

249
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!