js异步和同步

168 阅读2分钟

任务进入执行栈----同步任务还是异步任务----同步的进入主线程,异步的进入Event Table并注册函数。当指定的事情完成时,Event Table会将这个函数移入Event Queue(消息队列)。主线程内的任务执行完毕为空,会去Event Queue读取对应的函数,进入主线程执行。上述过程会不断重复,也就是常说的Event Loop(事件循环)。

遇到同步任务直接执行,遇到异步任务分类为宏任务(macro-task)和微任务(micro-task)。
宏任务:整体的Script setTimeout setInterval
微任务:Promise process.nextTick

image.png

1console.log('主线程console');
setTimeout(function() {
    console.log('宏任务setTimeout');  //先遇到setTimeout,将其回调函数注册后分发到宏任务Event Queue
                                      //如果setTimeout设置时间,那它会先把函数放到宏任务Event Table,等时间到了再放入宏任务Event Queue里面
})
new Promise(function(resolve) {
    console.log('微任务promise');     //new Promise函数立即执行,promise本质上是同步的
    resolve();			      //必须resolve执行才能执行then
}).then(function() {
    console.log('微任务then');        //then函数分发到微任务Event Queue
})
//执行顺序结果: 主线程console、微任务promise、微任务then、宏任务setTimeout

2、证明promise本质上是同步的 ``

setTimeout(function() {
    console.log('宏任务setTimeout');  //先遇到setTimeout,将其回调函数注册后分发到宏任务Event Queue
                                      //如果setTimeout设置时间,那它会先把函数放到宏任务Event Table,等时间到了再放入宏任务Event Queue里面
})
new Promise(function(resolve) {
    console.log('微任务promise');     //new Promise函数立即执行,promise本质上是同步的
    resolve();			      //必须resolve执行才能执行then
}).then(function() {
    console.log('微任务then');        //then函数分发到微任务Event Queue
})
console.log('主线程console');
 
//执行顺序结果: 微任务promise、主线程console、微任务then、宏任务setTimeout

async是基于promise封装而来的,所以本质也是一个同步任务

async function async1() {
    console.log('async1 start')
    await async2()
    console.log('async1 end')
}
async function async2() {
    console.log('async2')
}
async1()
console.log('script end')
//输出的结果是async1 start、async2、script end、async1 end