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

140
Views
How to make JS stack really "wait" for the ending of an asynchronous function?

I'm learning how Asynchronous JavaScript works, and I'm trying to print to the console the numbers 1 and 2 (in this order). The function that logs 1 has a setTimeout, and as such, the order is always inverted. I know why this happens. I just don't know how to make it work as I would like to. I've tried this:

function first(){
    setTimeout(
            ()=>console.log(1),
            1000
    )

    return Promise.resolve(true)
}

function second(){
    console.log(2)
}


function a(){
    first()
    .then(second())
}

console.log("running...")
a()

and also this:

async function first(){
    setTimeout( 
        ()=>console.log(1),
        2000
    )

    return true            
}

function second(){
    console.log(2)
}


async function a(){
    await first()
    second()
}

console.log("running...")
a()

Both of which print

running...
2
1

The desired output would be

running...
1
2

What am I doing wrong?

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

0

Would callbacks not be acceptable?

function first(callback) {
  setTimeout(() => {
    console.log(1);
    callback();
  }, 2000);
}

function second() {
  console.log(2)
}
// When first is completed, second will run.
first(() => second());
console.log("This can run at any time, while we're waiting for our callback.");

about 4 years ago · Juan Pablo Isaza Report

0

Read about Js promises (developer.mozilla.org) here his your code working

function first(){
    return new Promise((resolve)=>{
                        console.log('waiting')
                        setTimeout( ()=>{console.log(1); resolve('waiting finished')}, 2000 )
                        }
                      );
                    }

function second(){
    console.log(2)
}


async function a(){
    await first().then(res => console.log(res))
    second()
}

console.log("running...")
a()

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!