笔记
宏任务:
script全部代码、setTimeout、setInterval、setImmediate(浏览器暂时不支持,只有IE10支持,具体可见MDN)、I/O、UI Rendering。
【记忆:一个U(UI Rendering)I(I/O)工程师在4S店】
微任务:
Process.nextTick(Node独有)、Promise、Object.observe(废弃)、MutationObserver(MDN链接)
【记忆:PPOM,其中MutationObserver作用是监听dom发生改变】
console.log('script start');
setTimeout(function() {
console.log('setTimeout');
}, 0);
new Promise((resolve)=>{
resolve();
console.log("new Promise");
}).then(function() {
console.log('promise1');
}).then(function() {
console.log('promise2');
});
console.log('script end');
// script start
// new Promise
// script end
// promise1
// promise2
// setTimeout
// 执行顺序
// script -> Promise callback -> setTimeout callback
console.log('script start')
async function async1() {
await async2()
console.log('async1 end')
}
async function async2() {
console.log('async2 end')
}
async1()
// async await 是Promise的语法糖
// 可以转换成
// new Promise((resolve)=>{
// console.log('async2 end');
// resolve();
// }).then(()=>{
// console.log('async1 end')
// })
setTimeout(function() {
console.log('setTimeout')
}, 0)
new Promise(resolve => {
console.log('Promise')
resolve()
})
.then(function() {
console.log('promise1')
})
.then(function() {
console.log('promise2')
})
console.log('script end')