首页 > Web开发 > 详细

js中宏任务,微任务,异步,同步,执行的顺序

时间:2020-03-24 17:58:48      阅读:60      评论:0      收藏:0      [点我收藏+]
 [微任务]包括:Promise ,    process.nextTick() *node.js里面的
 [宏任务]包括:整体代码script,  setTimeout    setInterval
 
技术分享图片
 
先输出同步,然后把异步的放到异步队列。然后先执行异步队列的微任务,再执行里面的宏任务
 
setTimeout(function(){
    console.log(‘set1‘)
    new Promise(function(resolve){
        resolve()
    }).then(function(){
        new Promise(function(resolve){
            resolve()
        }).then(function(){
            console.log(‘then4‘)
        })
        console.log(‘then2‘)
    })
})

new Promise(function(resolve){
    console.log(‘pr1‘);
    resolve()
}).then(function(){
    console.log(‘then1‘)
})

setTimeout(function(){
    console.log(‘set2‘)
})

console.log(2)
 
运行上述一段代码,先输出同步,然后把异步的放到异步队列。然后先执行异步队列的微任务,在执行里面的宏任务,最后输出:
宏任务[set1,set2]
微任务[then1][then2][then4]
结果: pr1,2,then1,set1,then2 ,then4,set2
 
 
 
 

js中宏任务,微任务,异步,同步,执行的顺序

原文:https://www.cnblogs.com/weiqian/p/12559510.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!