关于promise题目的打印

原题,请问打印顺序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
new Promise((resolve, reject) => {
    console.log("1")
    resolve()
}).then(() => {
    console.log("2")
    new Promise((resolve, reject) => {
        console.log("3")
        resolve()
    }).then(() => {
        console.log("4")
    }).then(() => {
        console.log("5")
    })

}).then(() => {
    console.log("6")
})
new Promise((resolve, reject) => {
    console.log("7")
    resolve()
}).then(() => {
    console.log("8")
})

下面是我自己的理解分析过程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
new Promise((resolve, reject) => {
    console.log("1") // -> 同步走到7
    resolve() // 存入2的promise
}).then(() => {
    console.log("2") // -> 同步走到3
    new Promise((resolve, reject) => {
        console.log("3") // -> 同步走到9
        resolve() // 存入4的promise,但是同步未走完,要走到9那里
    }).then(() => {
        console.log("4") // -> 同步走完,出栈6
// resolve() // 4先于6存入,所以先执行4,后执行6,然后存入5
    }).then(() => {
        console.log("5") // -> end
// resolve() // 没有then不需要存入
    })
// console.log("9") // 同步走完,出栈8
// resolve() // 存入6。
/**
* 其实实现promise的时候,每个then都是Promise,也就是可以考虑每* 个then执行完都会执行一次resolve,把后面的then入栈
*/

}).then(() => {
    console.log("6") // -> 同步走完,出栈5
// resolve() // 没有then不需要存入
})
new Promise((resolve, reject) => {
    console.log("7") // -> 同步走完,出栈2
    resolve() // 存入8的promise
}).then(() => {
    console.log("8") // -> 同步走完,出栈4
// resolve() // 没有then不需要存入
})