new Promise((resolve,reject) => {
console.log('outer promise')
resolve()
})
.then(() => {
console.log('outer 1 then')
new Promise((resolve,reject) => {
console.log('in promise')
resolve()
})
.then(() => {
console.log('in 1 then')
return Promise.resolve()
})
.then(() => {
console.log('in 2 then')
})
})
.then(() => {
console.log('outer 2 then')
})
.then(() => {
console.log('outer 3 then')
})
.then(() => {
console.log('outer 4 then')
})
Here are my explanation:
1.Execute the new Promise
,output outer promise
2.Execute the first outer then,its callback go to the microtask queue.The second outer then,the third outer then and the fourth outer then execute later,but all of their callback don't go to the queue since each promise returned by each then
still in pending state.
3.Execute the callback of the first outer then,and output outer 1 then
.After that,new Promise
will output in promise
4.Execute the first inner then,its callback go to the microtask queue.The callback of the second inner then don't go to the queue
5.Now,the callback of the first outer then has totally finished,which means the promise returned by the first outer then has resolved.Thus,the callback of the second outer then go to the queue
6.Execute the first task of the queue,it will output outer 2 then
and makes the callback of the third then go to the queue.Next,execute the callback of the second inner then,it will output in 2 then
7.Execute the callback of the third outer then,it will output outer 3 then
and makes the callback of the fourth then go to the queue.
8.At last,execute the callback of the fourth outer then,it will output outer 4 then
Therefore,the output order should be:
outer promise
outer 1 then
in promise
in 1 then
outer 2 then
in 2 then
outer 3 then
outer 4 then
But it actually ouput:
outer promise
outer 1 then
in promise
in 1 then
outer 2 then
outer 3 then
outer 4 then
in 2 then
What I am confused is why in 2 then
will output at last? And why outer 2 then
,outer 3 then
,outer 4 then
will output continuously? This is different from what I have thought about event loop.I thought the result is something to do with the statement return Promise.resolve()
,but I don't know what the statement exactly do and why it will influenced the output order.