关于两个Promise链的执行顺序问题

152 阅读1分钟

下列代码打印结果是什么:

      new Promise((resolve,reject)=>{
        throw new Error("异常了")
      }).then(res=>{
        console.log('上面第一个then')
      }).catch(err=>{
        console.log('err: ', err); 
      }).then(res=>{
        console.log("上面第二个then"); 
      })
      console.log('--------------------------'); 
      new Promise((resolve,reject)=>{
          resolve()
      }).then(res=>{
        console.log('下面第一个then');  
      }).then(res=>{
        console.log('下面第二个then');   
        return new Promise((resolve,reject)=>{
          reject("失败了")
        })
      }).catch(err=>{
        console.log('err: ', err);  
      }).then(res=>{
        console.log("最后一步"); 
      })

我的理解是,两个Promise并发同层执行,也就是执行第一个P的第一个then和第二个P的第一个then一起,发现第一个P的不执行,就先执行第二个P的了。然后开始看第一个P的第二个catch和第二个P的第二个then,都有执行,那就先执行上面的,后执行下面的。

这理解有点勉强,我知道这是微任务相关的,问了几个人也解释不清楚,只能这样片面的理解了至少以后遇到就知道顺序了,如果有能解析的大大可以留言评论区,以下是打印结果:

image.png