Case analysis of synchronous and asynchronous execution

Case analysis of synchronous and asynchronous execution

JavaScript is single-threaded. It first processes synchronization and then processes tasks in the task queue. The task queue is divided into macro task queue and micro task queue. The priority of micro task queue is higher than that of macro task queue.

console.log('1');   //第一位=》直接输出1

setTimeout(() => {
    
    //定时器,异步函数,先存放宏任务队列
    console.log('2');第五位=》宏任务队列开始,输出2
    process.nextTick(() => {
    
    
        console.log('3');第七位=》直接输出3
    })
    new Promise((resolve) => {
    
    
        console.log('4');第六位=》同步输出4
        resolve();
    }).then(() => {
    
    
        console.log('5')第八位=》直接输出5
    })
})
process.nextTick(() => {
    
    //异步,存放微任务队列
    console.log('6');第三位,先处理微任务队列,打印6
})
new Promise((resolve) => {
    
    //Promise为同步函数,直接打印7
    console.log('7');//第二位=》直接输出7
    resolve();
}).then(() => {
    
    //promise.then为异步,存放微任务队列
    console.log('8');第四位=》直接输出1,微任务队列按顺序,打印8
})

setTimeout(() => {
    
    //定时器,异步函数,先存放宏任务队列
    console.log('9');//第九位=》直接输出9
    process.nextTick(() => {
    
    
        console.log('10');//第十二位=》直接输出10
    })
    new Promise((resolve) => {
    
    
        console.log('11');//第十位=》直接输出11
        resolve();
        console.log('12');//第十一位=》直接输出12
    }).then(() => {
    
    
        console.log('13')//第十三位=》直接输出13
    })
})
控制台输出结果:1 7 6 8 2 4 3 5 9 11 12 10 13
事件循环,第一次循环输出1 7 6 8,第二次循环输出2 4 3 5,第三次循环输出9 11 12 10 13

Guess you like

Origin blog.csdn.net/Wonder_BBJ/article/details/108263345
Recommended