setTimeout(function(){
console.log('set1')
})
var p = new Promise(function(resolve,reject){
resolve()
})
setTimeout(function(){
console.log('set2');
new Promise(function(resolve,reject){
resolve()
}).then(function(){
console.log('promise1')
})
})
setTimeout(function(){
console.log('set3')
})
p.then(function(){
console.log('promise')
})
console.log('1234')
如代碼所示 最後運行結果爲
1234 promise set1 set2 promise1 set3
原因如下:
1,promise是微任務,setTime是宏任務
2,js執行會先執行微任務,微任務隊列空了, 再去看宏任務
所以:同步執行完,先去執行微,所以先promise,微任務隊列空了,去執行宏,所以接着set1,set2,set2裏又加入一個微任務,微任務隊列有了,就先做微任務,所以在是promise1,最後在set3