Promise链式调用嵌套的问题,哈哈哈 虽然这个问题在正常开发中应该不会遇到,但是谁让咱们是程序员呢, 就是喜欢搞事情,这个问题就是搞Promise链式嵌套调用
new Promise(function Promise1(resolve,reject){
console.log("promise1")
resolve()
}).then(function Then1(){
console.log("then1")
new Promise(function Promise2(resolve,reject){
console.log("promise2")
resolve()
}).then(function Then11(){
console.log("then11")
}).then(function Then111(){
console.log("then111")
}).then(function Then1111(){
console.log("then1111")
})
}).then(function Then12(){
console.log("then12")
})
new Promise(function Promise3(resolve,reject){
console.log("promise3")
resolve()
}).then(function Then2(){
console.log("then2")
}).then(function Then21(){
console.log("then21")
}).then(function Then211(){
console.log("then211")
})
执行结果
结果中我们发现个问题就是为什么then11 是优先于then12执行的呢???
我们来画一下这一堆链式调用的链子,每一个红框都是自上而下的执行顺序。
从这个执行顺序当中我们,可以看出应该是先执行Then12 ,再执行Then11的呀,可是我们就忽略Promise中Then的定义:
then里面的是回调函数,它需要等上一层执行完才调用下面的then
在第二层Then1的时候,Then12 还没有建立,因为Then1中有同步代码Promise2,要走完Promise2,Promise2调用了个Then11, 才会建立Then12,所有再输出的时候,Then11 是优先于 Then12的