众所周知js是单线程,但js是能够执行同步和异步任务的,同步的任务众人皆知是按照顺序去执行的;
而异步任务的执行,是有一个优先级的顺序的,包括了宏任务(macrotasks)和微任务(microtasks)面试
宏任务: setTimeout, setInterval, setImmediate, I/O, UI rendering 微任务: Promises.(then catch finally), process.nextTick, MutationObserver
宏任务和微任务的区别在于在事件循环机制中,执行的机制不一样
咱们在工做经常使用到的宏任务是setTimeout
,而微任务是Promise.then
注意这里是Promise.then,也就是说new Promise在实例化的过程当中所执行的代码是同步的,而在then中注册的回调函数才是异步。异步
看下面的代码,面试题里常常见的函数
setTimeout(() => console.log(1)) new Promise((resolve) => { resolve() console.log(2) }).then(() => { console.log(3) }) console.log(4)
new Promise在实例化过程当中过程当中执行的代码是同步的,因此先打印出2,而后是最后一行的4,全部同步任务已经执行完成了,接着执行微任务也就是.then()里的回调函数,因此打印4,最后执行宏函数setTimeout,最后打印出1线程
因此上面代码块的结果是2 4 3 1
code
new Promise(resolve => { resolve() console.log(1) }).then(_ => { console.log(2) }) new Promise(resolve => { resolve() console.log(3) }).then(_ => { console.log(4) }) console.log(5); setTimeout(_ => console.log(6)) setTimeout(_ => console.log(7))
1 3 5 2 4 6 7
server
经过上面两个示例能够简单的理解宏任务和微任务的执行顺序,若是还想了解更深层的东西,能够了解一下js的事件循环,这里就再也不多说了。队列