事件循环
浏览器中的事件循环
macro-task大概包括:
- script(整体代码)
- setTimeout
- setInterval
- setImmediate
- I/O
- UI render
micro-task大概包括:
- process.nextTick
- Promise
- Async/Await(实际就是promise)
- MutationObserver(html5新特性)
题目
// 题目一:
async function async1() {
await async2()
console.log('async1 end')
}
async function async2() {
console.log('async2 end')
await async3();
console.log('async2 end1')
}
async function async3() {
console.log('async3 end')
}
async1()
new Promise(resolve => {
console.log('Promise')
resolve()
})
.then(function() {
console.log('promise1')
})
.then(function() {
console.log('promise2')
})
// async2 end
// async3 end
// Promise
// async2 end1
// promise1
// async1 end
// promise2
// 题目二:
async function async1() {
await async2()
console.log('async1 end')
}
async function async2() {
console.log('async2 end')
// await async3();
Promise.resolve().then(() => { console.log('async2 end1') })
}
async function async3() {
console.log('async3 end')
}
async1()
new Promise(resolve => {
console.log('Promise')
resolve()
})
.then(function() {
console.log('promise1')
})
.then(function() {
console.log('promise2')
})
// async2 end
// Promise
// async2 end1
// async1 end
// promise1
// promise2
// 题目三:
async function async1() {
await async2()
console.log('async1 end')
}
async function async2() {
console.log('async2 end')
// await async3();
return Promise.resolve().then(() => { console.log('async2 end1') })
}
async function async3() {
console.log('async3 end')
}
async1()
new Promise(resolve => {
console.log('Promise')
resolve()
})
.then(function() {
console.log('promise1')
})
.then(function() {
console.log('promise2')
})
// async2 end
// Promise
// async2 end1
// promise1
// promise2
// async1 end
疑惑点:async2 中
await跟return Promise有什么区别,为啥async1 end输出会往后一点?猜测:
return Promise比await中间多产生一个异步,比如多一个then。