JavaScript把任务分为同步任务和异步任务,异步任务又被进一步划分为宏任务和微任务。
宏任务:
1.异步Ajax请求
2.setTimeOut,setIternal
3.文件操作
微任务:
1.promise.then,.catch,和.finally
2.process.nextTick
宏任务和微任务是交替执行的。
每一个宏任务执行完后都会检查是否存在待执行的微任务,如果有,则执行完所有微任务后,在执行下一个宏任务。
代码示例与运行1:
setTimeout(function(){ console.log('1') }) new Promise(function(resolve){ console.log('2') resolve() }).then(function(){ console.log('3') }) console.log('4')//运行结果: //2 //4 //3 //1
只要new一个promise的实例,后面的function会立马被执行,所以4,5,6行代码属于同步任务,输出2。另外,最后一行输出4。.then被加入微任务队列,计时器被加入宏任务队列。
同步任务:输出2,4
异步任务:先执行微任务输出3,再执行宏任务输出1
所以最后输出结果为2431.
代码示例与运行2:
1 console.log('1') 2 setTimeout(function(){ 3 console.log('2') 4 new Promise(function(resolve){ 5 console.log('3') 6 resolve() 7 }).then(function(){ 8 console.log('4') 9 }) 10 }) 11 new Promise(function(resolve){ 12 console.log('5') 13 resolve() 14 }).then(function(){ 15 console.log('6') 16 }) 17 setTimeout(function(){ 18 console.log('7') 19 new Promise(function(resolve){ 20 console.log('8') 21 resolve() 22 }).then(function(){ 23 console.log('9') 24 }) 25 })
运行结果为:156234789
分析:首先执行同步任务输出1和5,执行完11,12,13行代码后,14,15行加入微任务执行队列,同步任务执行完后,再执行微任务队列中的微任务输出6,清空微任务队列。之后执行宏任务(2到10行代码),执行其中的同步任务,输出2和3。把第7,8行代码放入微任务执行队列,在执行下一个宏任务之前,执行微任务队列中的任务,输出4。同理输出7,8,9.