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