js事件循环(Event Loop)及微任务和宏任务

1. 事件循环 (Event Loop)

js是单线程的;js任务是一个一个顺序执行;所有的任务队列可以分为同步任务和异步任务。同步任务会进入主线程中执行;异步任务回通过任务队列(Event Queue)的机制进行协调执行
js事件循环(Event Loop)及微任务和宏任务_第1张图片

  • 同步代码,一行一行放在Call Stack 执行
  • 遇到异步,会先“记录”下,等待时机(定时、网络请求等)
  • 时机到了,就移动到Callback Queue

(1)DOM事件和event loop

  • 异步( setTimeout , ajax 等)使用回调,基于event loop
  • DOM事件也使用回调,基于event loop

(2)async/await

  • Promise then catch链式调用,但也是基于回调函数
  • async/await是同步语法,彻底消灭回调函数

(3)async/await和Promise的关系

  • async/await是消灭异步回调的终极武器
  • 执行async函数,返回的是Promise对象
  • await 相当于Promise 的 then
  • try…catch可捕获异常,代替了Promise 的catch

2.微任务(microTask)和宏任务(macroTask)

js事件循环(Event Loop)及微任务和宏任务_第2张图片

异步任务又分为 微任务和宏任务

  • 宏任务: setTimeout , setInterval , Ajax,DOM事件 ,整体代码等
  • 微任务: Promise async/await 等
  • 微任务先于宏任务执行

(1)为什么微任务先执行?

  • 微任务是ES6语法规定的
  • 宏任务是由浏览器规定的,要经过webAPIs

js事件循环(Event Loop)及微任务和宏任务_第3张图片
js事件循环(Event Loop)及微任务和宏任务_第4张图片

3.常见面试题

(1)promise then和catch的连接

Promise.resolve().then((resolve)=>{
   console.log(1); // 1
}).catch(()=>{
   console.log(2);//不会打印这里
}).then(()=>{
   console.log(3);//3
})
Promise.resolve().then(()=>{
   console.log(1);// 1
   throw new Error('error1')
}).catch(()=>{
   console.log(2);// 2
}).then(()=>{
   console.log(3);// 3
})
Promise.resolve().then(()=>{
   console.log(1);// 1
   throw new Error('error1')
}).catch(()=>{
   console.log(2);// 2
}).catch(()=>{
   console.log(3);// 此处不会打印
})

(2)async/await语法

async function fn(){
  return 100;
}
  (async function(){
  const a = fn()
  const b = await fn()
  console.log(a);//Promise {: 100} 返回promise对象
  console.log(b);//100
})()
(async function(){
   console.log('start');//start
   const a = await 100;
   console.log("a",a);//100
   const b = await Promise.resolve(200);
   console.log("b",b);//200
   const c = await Promise.reject(300);
   console.log("c",c);//不打印
   console.log("end");//不打印
})()

(3)promise和setTimeout的顺序

console.log(100);
setTimeout(()=>{
  console.log(200);
})
Promise.resolve().then(()=>{
  console.log(300);
})
console.log(400);
//打印顺序 100-400-300-200

(4)外加 async/await 的顺序问题

   async function async1(){
      console.log('async1 start');//2
      await async2()
      console.log('async1 end')//6
    }
    async function async2(){
      console.log('async2');//3
    }
    console.log('script start');//1

    setTimeout(function(){
      console.log('settimeout');//8
    },0)
    async1()

    new Promise(function (resolve){
      console.log('promise 1');//4
      resolve()
    }).then(function (){
      console.log('promise 2');//7
    })
    console.log("script end");//5

出处:B站 https://www.bilibili.com/video/BV1Si4y1c7rh?spm_id_from=333.337.search-card.all.click

你可能感兴趣的:(Js,javascript,前端,node.js)