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
Proper use of async JS to ensure function calls wait for previous functions to complete (resolve?)

Trying to learn proper async/await JavaScript to run functions in sequence when an early function in the sequence would be delayed (using setTimeout to simulate). I'm not getting the expected results (still getting "first", "second", "this should run first?" - see code).

What am I missing? Do I have the wrong idea about this?

Thanks in advance!

const zeroFunction = () => {
    setTimeout(() => {
        return new Promise((resolve) => {
            console.log("This should run first?");
            resolve();
        }); 
}, 2000)}

const firstFunction = () => {
    return new Promise((resolve) => {
        console.log("first");
        resolve();
    }) 
}

const secondFunction = () => {
    return new Promise((resolve) => {
        console.log("second");
        resolve();
    })
}

async function fnAsync() {
    await zeroFunction();
    await firstFunction();
    secondFunction();
}

fnAsync();
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

zeroFunction is currently returning undefined implicitly, not a Promise. Inverse the wrapping of the setTimeout and Promise constructor and it should work as expected.

const zeroFunction = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("This should run first?")
      resolve()
    }, 2000)
  })
}
const firstFunction = () => {
  return new Promise((resolve) => {
    console.log("first")
    resolve()
  })
}

const secondFunction = () => {
  return new Promise((resolve) => {
    console.log("second")
    resolve()
  })
}

async function fnAsync() {
  await zeroFunction()
  await firstFunction()
  secondFunction()
}

fnAsync()

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!