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

124
Views
Aren't async/await functions put in event loop?

I am very new to asynchronous Javascript and was studying the async/await feature. I have kind of a basic question about the code attached. When I run the code, I think the async function should wait (because of await keyword) and be put in micro-task queue, thus suspending its execution. So, the call stack should execute the main thread's console.log('first') , then print the output of randomFunction() when call stack is empty and micro-task queue starts executing and finally invoke the callback. So I thought the output should've been first, (the random number) and then second. But to my surprise that isn't the case. Can someone please explain why this happened in a simplified manner ?

function randomFunction() {
  //generates a random number and prints it
  const number = Math.floor(Math.random() * 100);
  console.log(number);
}

async function asyncWithCallback(callback) {
  await randomFunction();
  callback();
}

function callback() {
  console.log('second');
}
asyncWithCallback(callback);
console.log('first');

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

await first evaluates the expression that follows it, and only then the async function returns (with a promise), suspending the function for later.

So the output of the randomFunction is produced synchronously, and then it proceeds as you describe: "first" is output synchronously as well.

Then the call stack becomes empty and we arrive in the "asynchronous phase": the engine processes the job in the PromiseJob queue, which resumes the async function, which calls callback where "second" is output.

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!