js 是一门单线程的非阻塞的脚本语言
单线程:只有一个主线程处理所有任务
非阻塞:有异步任务,主线程挂起这个任务,等异步返回结果再根据一定规则执行
- 都是异步任务
-
- 宏任务:script 标签,setTimeout,setInterval,setImmediate,I/O,接口调用
- 微任务:process.nextTick,Promise.then() catch(),Async/Await,Object.observe
-
- 注意:Promise 本身是同步任务,then,catch,finally 是异步任务
- async 中 await 右边代码是同步任务,之后代码是异步任务
主线程执行顺序:一个宏任务(script 标签)-> 同步任务 -> 微任务 -> 一个宏任务 -> 宏任务中的微任务(如果有) -> 下一个宏任务 -> ..... 直到 js 事件执行完成。
- async function async1(){
- console.log('1') // 同2
- await async2()
- console.log('2') // 微1
- }
- async function async2(){
- console.log('3') // 同3
- }
- console.log('4') // 同1
- setTimeout(function(){
- console.log('5') // 宏1
- },0)
- setTimeout(function(){
- console.log('6') // 宏2
- },3)
- async1();
- new Promise(function(resolve){
- console.log('7') // 同4
- resolve();
- console.log('8') // 同5
- }).then(function(){
- console.log('9') // 微2
- })
- console.log('10') // 同6
- // 输出:4,1,3,7,8,10,2,9,5,6