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

232
Views
If I use async/await, it doesn't run in order

I have a question about the async/await execution.

example codes

async firstMethod(){
  new Promise((resolve, reject)) => {
     setTimeout(() => {
        resolve("test1");
     }, 3000);     
  });
}

async secondMethod() {
  new Promise((resolve, reject)) => {
     setTimeout(() => {
        resolve("test2");
     }, 1000);     
  });
}

await firstMethod();
await secondMethod();

So, When the two methods are executed, the following results are obtained.

test2
test1

However, if a return is attached, the result value is as follows.

async firstMethod(){
  return new Promise((resolve, reject)) => {
     setTimeout(() => {
        resolve("test1");
     }, 3000);     
  });
}

async secondMethod() {
  return new Promise((resolve, reject)) => {
     setTimeout(() => {
        resolve("test2");
     }, 1000);     
  });
}

await firstMethod();
await secondMethod();
test1
test2

Why is that? I'd appreciate it if you could explain it.

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

0

In the first case you just await the outer promises (that are the firstMethod and secondMethod functions) and the inner promises created by new Promise do not get awaited, and simply run to completion in the background.

In the second case, because of promise unwrapping you await the returned inner promises together with the outer function promises.

about 4 years ago · Juan Pablo Isaza Report

0

The reason why in the first example those 2 functions do not run in order is because you are not waiting for anything. If you try to remove the async from the function definition in the first example you will get the same result because the function does not need the async because it does not require an await. What you could do to have the same result has the second example is by adding a await before the new Promise.

Note: You also do not need the async in the second example because you are not waiting for anything, you are just returning a Promise in which you wait outside the scope.

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!