Home > Back-end >  multiple awaits are running in parallel
multiple awaits are running in parallel

Time:06-29

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)

CodePudding user response:

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()

  • Related