Why is the following code executed in order 0123456
Promise.resolve().then(() = > { // line1
console.log(0);
return Promise.resolve(4); // line2
}).then((res) = > { // line3
console.log(res)
})
Promise.resolve().then(() = > { //line4
console.log(1)
}).then(() = > { // line5
console.log(2)
}).then(() = > { // line6
console.log(3)
}).then(() = > { // line7
console.log(5)
}).then(() = > { // line8
console.log(6)})Copy the code
-
The event queue is represented as [line1__,line4, P1], in which events with __ (such as line1__) are completed events. For the sake of viewing the execution process, the event queue is represented as __.
- 1, line1 execute, then task adds event queue, then event queue [line1]
- 2,line4 execute, then task add event queue, then event queue [line1,line4]
- 3. If no synchronization task exists, execute the task in the event queue
- [line1__,line4, P1] [1, 2, 3] [1, 3, 4]
- 5, continue the execution of task queue line4, output 1, find the task line5, join the event queue, then the event queue [line1__,line4__, P1,line5]
- [line1__,line4__,p1__,line5,p2] [line1__,line4__,p1__,line5,p2]
- [line1__,line4__,p1__,line5__,p2,line6] [line1__,line4__,p1__,line5__,p2,line6]
- [line1__,line4__,p1__,line5__,p2__,line6,line3] [line1__,line4__,p1__,line5__,p2__,line6,line3]
- [line1__,line4__,p1__,line5__,p2__,line6__,line3,line7] [line1__,line4__,p1__,line5__, line6__,line3,line7]
- [line1__,line4__,p1__,line5__,p2__,line6__,line3__,line7]
- [line1__,line4__,p1__,line5__,p2__,line6__,line3__,line7__,line8]
- [line1__,line4__,p1__,line5__,p2__,line6__,line3__,line7__,line8__]
532