The small sample:
console.log(1)
setTimeout(function() {
console.log(2)
}, 0)
console.log(3)
Copy the code
Macro tasks: the main thread code, setTimeout, etc., belong to macro tasks. The next macro task will be considered after the execution of the previous macro task
Microtask: the content to be performed by promise.then. catch belongs to the microtask. The microtask that meets the conditions will be added to the end of the current macro task to be executed
EventLoop queue
Example 1:
Console. log(1) setTimeout(function() {console.log(2) // macro task}, 0) const p = new Promise((resolve, resolve, Reject) => {resolve(1000)}) p.chen (data => {console.log(data) // microtask}) console.log(3)Copy the code
Example 2:
async function fn () {
console.log(111)
}
fn()
console.log(222)
Copy the code
Example 3:
async function fn () {
const res = await 2
console.log(res)
}
fn()
console.log(222
Copy the code
Example 4:
Async function fn () {console.log(' console.log ') const res = await fn2() console.log(res) // async function fn2() { console.log('gaga') } fn() console.log(222)Copy the code
An async function starts asynchrony only if it goes from “await”