0

Can anyone tell me why this code outputs the following? I am completely lost on async functions and close to just giving up.

The first await does what I expect and waits 1 second before executing. However, somehow 301 is outputted before the then before it is executed which seems to completely defy the literal definition of then. Done is outputted then somehow it goes back and executes the second then statement.

async function test() {

  const promise1 = await new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('foo');
      console.log('First await executed')
    }, 1000)
  }).then(() => {
    new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('foo');
        console.log("This was executed")
      }, 1000)
    })
  }).then(() => Promise.resolve(301));

  console.log(promise1)

  await setTimeout(() => console.log(1000), 1000)

  console.log("Done");
}

test()
Yousaf
  • 27,861
  • 6
  • 44
  • 69
  • You are not returning the Promise within the first `.then()`, so it is completely unrelated to the other Promise chain. – Ivar Apr 06 '22 at 12:10
  • Doesn't resolve pass its value? –  Apr 06 '22 at 12:13
  • Not if you don't do anything with the Promise you are constructing. The `then()` callback will be executed in order, but it only constructs a Promise and then continues. If you want it to wait for the promise before continuing, you'll need to either `await` it, or `return` it. – Ivar Apr 06 '22 at 12:14

0 Answers0