js的微任务宏任务执行机制解析

console.log('1')

setTimeout(function() {    //  宏任务
	console.log('2')
	process.nextTick(function() {   // 微任务
		console.log('3')
	})
	
	new Promise(function(resolve) {   //  同步
		console.log('4')
		resolve()
	}).then(function () {   //  微任务
		console.log('5')
	})
})

process.nextTick(function () {  // 微任务
	console.log('6')
}) 

new Promise(function(resolve) {  // 同步 
	console.log('7')
	resolve()
}).then(function () {   // 微任务
	console.log('8')
})

setTimeout(function () { // 宏任务
	console.log('9')
	process.nextTick(function () {   // 微任务
		console.log('10')
	})
	new Promise(function(resolve) { // 同步
		console.log('11')
		resolve()
	}).then(function() {  // 微任务
		console.log('12')
	})
})


答案: 1、7、6、8、2、4、9、11、3、5、10、12
解析: 先同步执行代码,如果有异步的放到异步队列里面,异步队列又分 微任务 和 宏任务。
在这里插入图片描述
先执行微任务,当前微任务执行完毕-》执行宏任务 =》 当前宏任务执行完,看有没有剩下的微任务,再执行完所有的微任务,再执行下一个宏任务。
言简意赅,凑合看吧。
同步-》微任务-》宏任务 -》微任务
这个是讲js单线程异步概念的链接如果想了解的可以看这个

晚上再补个图,下班。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值