0

When trying to understand async/await, I tried this block of code that didn't behave the way I expected it to.

let test = async function () {
  let result = new Promise((resolve, reject) => {
    setTimeout(() => resolve('done1'), 2000)
  })

  let result2 = new Promise((resolve, reject) => {

    setTimeout(() => resolve('done2'), 2500)
  })

  let x1 = await result
  console.log(x1)


  let x2 = await result2
  console.log(x2)

}

test()

I was expecting the console to display done1 after 2seconds, then display done2 2.5 seconds after done1. Instead, It displayed done1 in 2seconds and done2 0.5seconds after that. Why does it behave like this, since I await the second setTimeout after displaying the first one?

Zikero
  • 15
  • 2

1 Answers1

1

When you create a new Promise, it starts to run it's code. When you have setTimeout inside it, actually the timer is going. When you use await before the Promise call, it waits until the promise will be resolved or rejected and then work.

You need to create each promise and after that wait for it.

let test = async function () {

  let result = new Promise((resolve, reject) => {
    setTimeout(() => resolve('done1'), 2000);
  });
  
  let x1 = await result;
  console.log(x1);

  let result2 = new Promise((resolve, reject) => {
    setTimeout(() => resolve('done2'), 2500);
  });

  let x2 = await result2;
  console.log(x2);

}

test()
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112