Skip to content

任务&异步

应用场景

  1. 网络请求
  2. 图片加载
  3. 定时任务

Pormise

三种状态:pending执行中、resolve成功、reject失败

加载图片

img.png

多步骤走向

img_1.pngimg_2.pngimg_3.png

微任务宏任务

JS是单线程,异步需要基于even loop实现异步回调

event loop执行过程

img_4.png

  1. 同步代码一行行在Call Stack执行
  2. 遇到异步先记录(定时、网络请求),时机到了移动到Callback Queue
  3. Call Stack为空,执行微任务(Promise)
  4. 尝试渲染DOM渲染
  5. even loop开始执行宏任务,将Callback Queue移动到Call Stack执行
  6. img_5.png

async和await

示例1

js
async function async1(){
  console.log('async1 start1') //2
  await async2()
  // await后面走微任务,等整个js执行完。
  await async3()
  console.log('async1 end')//6
}
async function async2(){
  console.log('async2 start')//3
}
async function async3(){
  console.log('async3 start')//5
}
console.log('script start')// 1
async1()
console.log('script end')//4

示例2

js
  (async function(){
    console.log('start') //1
    const a = await 100
    console.log('a',a) //2  (a,100)
    const b = await Promise.resolve(200)
    console.log('b',b)//3 (b,200)
    const c = await Promise.reject(300) //报错
    console.log('c',c) //不执行
    console.log('end')//不执行
  })()

示例3

img_9.png

异步循环

img_8.png