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


 [微任务]包括: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
 
 
 
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM