Javascript runs an event loop.
Here is my guess.
Promise.resolve()
creates a promise which will be resolved in the next iteration. And every then block will be execute in the next iteration after the previous block finish. So here is the execution order:
Iteration 1: Created 2 promises (name them A and B) which will be resolved in Iteration 2
Iteration 2: Promise A resolves. Promise B resolves
Iteration 3: then
block of Promise A executes, which prints 0 and creates a new promise (name it C) which will be resolved in Iteration 4. First then
block of the Promise B executes, which prints 1.
Iteration 4: Second then
block of Promise B executes, which prints 2. Promise C resolves. (Since Promise C is added to the event loop later than Promise B, Promise B resolves before Promise C)
Iteration 5: Third then
block of Promise B executes, which prints 3. then
block of Promise C executes, which prints 4.
Iteration 6: Forth then
block of Promise B executes, which prints 5.
Iteration 7: Fifth then
block of Promise B executes, which prints 6.