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

83
Views
multiple awaits are running in parallel

I'm trying to learn async/await and promises and unable to make run multiple async functions in serial.

function firstFunction () {
  return new Promise((resolve, reject) => {
    setTimeout(() => console.log('first'), 2000)
    resolve()
  })
}

function secondFunction () {
  return new Promise((resolve, reject) => {
    setTimeout(() => console.log('second'), 1000)
    resolve()
  })
}

async function main() {
  await firstFunction()
  await secondFunction()
}

main()

Output I am getting is

second
first

Since there's an await for firstFunction(), I'd expect the promise of firstFunction() to finish before going to secondFunction().

Can someone point out why they ran in parallel and how to make them run one after the other? (ran in node v18.3.0)

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

0

You need to move your resolve() call inside setTimeout() function. Here is the fixed code:

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

function secondFunction () {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('second');
      resolve();
    }, 1000);
  })
}

async function main() {
  await firstFunction()
  await secondFunction()
}

main()

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!