setTimeout和promise async的循环次序

按主栈序列进行,
遇见log直接输出,
遇见settimeout的放入宏任务,
遇见promise进行分析,新定义的输出,
遇见resolve的,then执行放入微任务,
主栈序列进行完毕后先进行微任务在进行宏任务,
同理遇见settimeout放入宏任务.
注意: 宏任务序列中要按照等待时间和先后顺序排序进行,微任务按照先后执行顺序排放

  console.log('#1')
  setTimeout(function() {            
       console.log('#2')            
       new Promise(function(resolve) {                
           console.log('#3')                
           resolve()            
               }).then(function() {                
                  console.log('#4')})        
               })         
           new Promise(function(resolve) {            
               console.log('#5')            
               resolve()        
                   }).then(function() {            
                      console.log('#6')            
                      setTimeout(function() {                
                      console.log('#7')            
                      })        
                   })         
           console.log('#8')

#1    #5  #8  #6  #2   #3  #4   #7

可以看出Promise比setTimeout()先执行。

因为Promise定义之后便会立即执行,其后的.then()是异步里面的微任务。

而setTimeout()是异步的宏任务

猜你喜欢

转载自blog.csdn.net/p_s_p/article/details/129400752