js异步之宏任务和微任务

面试题

写出console.log的输出顺序

console.log(100);	// 1

setTimeout(()=>{
    console.log(200);	// 4
})

setTimeout(()=>{
    console.log(201);	// 5
})

Promise.resolve().then(()=>{
    console.log(300);	// 3
})

console.log(400);	// 2

// 100 400 300 200 201

什么是宏任务和微任务

宏任务:setTimeout, setInterval, Ajax, DOM事件
微任务:Promise async/await
微任务执行时机比宏任务要早(先记住)

异步和单线程

异步和单线程是相辅相成的,js是一门单线程脚本语言,所以需要异步来辅助

异步和同步的区别:

  • 异步不会阻塞程序的执行
  • 同步会阻塞程序的执行

使用异步的场景

定时任务:setTimeout,setInverval
网络请求:ajax请求,动态<img>加载
事件绑定

事件循环

同步和异步任务分别进入不同的执行“场所”,同步进入主线程,
异步进入Event Table并注册函数。当指定的事情完成时,
Event Table会将这个函数移入任务队列(Event Queue)。
主线程内的任务执行完毕为空,就去任务队列(Event Queue)读取对应的函数,
进入主线程执行

面试题

//请写出输出内容
   async function async1() {
       console.log('async1 start');
       await async2();
       console.log('async1 end');
   }
   async function async2() {
       console.log('async2');
   }
   
   console.log('script start');
   
   setTimeout(function() {
       console.log('setTimeout');
   }, 0)
   
   async1();
   
   new Promise(function(resolve) {
       console.log('promise1');
       resolve();
   }).then(function() {
       console.log('promise2');
   });
   console.log('script end');

//输出结果为:
	
// 首先执行同步的 在执行异步
// promise是同步的,但是里的四个api是异步的
// async await 也是同步的 但是会先执行调用的 在执行下面的代码
script start
async1 start
async2
promise1
script end
async1 end
promise2
setTimeout
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值