1

new Promise((resolve, reject) => {
  console.log("promise1")
  resolve()
}).then(() => {
  console.log("then11")
  new Promise((resolve, reject) => {
    console.log("promise2")
    resolve()
  }).then(() => {
    console.log("then21")
  }).then(() => {
    console.log("then23")
  })
}).then(() => {
  console.log("then12")
})

The above code output is following, When I test my understanding of micro task and macro task with promise and I can not get the correct output.

// "promise1"
// "then11"
// "promise2"
// "then21"
// "then12"
// "then23"

To be more specific, I am confused about the last 3 outputs. Thanks for the help!

// "then21"
// "then12"
// "then23"
Barmar
  • 741,623
  • 53
  • 500
  • 612
Sean Liu
  • 831
  • 1
  • 11
  • 23
  • 2
    What is "the correct output" ?? – Samathingamajig Aug 10 '21 at 22:00
  • 1
    You only get guaranteed order of resolved promises from the same chain. What you have is two unconnected chains of promises, so you should definitely not rely on them to be in any particular order. – VLAZ Aug 10 '21 at 22:08
  • 1
    What is your understanding of micro tasks (there are no macro tasks in the code btw), and to what output would that lead that you had expected? We can't help you clarify your misunderstanding if you don't explain how you think it works. – Bergi Aug 10 '21 at 22:15

1 Answers1

2

If you're looking for this output:

// "promise1"
// "then11"
// "promise2"
// "then21"
// "then23"
// "then12"

Then return the Promise inside your first .then(, like this:

new Promise((resolve, reject) => {
  console.log("promise1")
  resolve()
}).then(() => {
  console.log("then11")
  return new Promise((resolve, reject) => {
    console.log("promise2")
    resolve()
  }).then(() => {
    console.log("then21")
  }).then(() => {
    console.log("then23")
  })
}).then(() => {
  console.log("then12")
})

The return returns the Promise made by the last .then( in the chain after your second new Promise. Your very last .then( will await the then23 .then(, then execute.

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34