js【详解】async await

为什么要使用 async await

async await 实现了使用同步的语法实现异步,不再需要借助回调函数,让代码更加易于理解和维护。

(async function () {
    // await 必须放在 async 函数中
    try {
        // 加载第一张图片
        const img1 = await loadImg1()
        // 加载第二张图片
        const img2 = await loadImg2()
    } catch (err) {
        console.error(err)
    }
})()

async await 使用要点

  • await 只能在 async 函数中使用

async await 语法特点

  • async 函数返回的都是 Promise 对象(若 async 函数内返回的不是 Promise ,则会自动将其封装为 Promise 再返回)
async function fn1() {
    return 100
}
console.log( fn1() ) // 相当于 Promise.resolve(100)
  • await 后跟 Promise 对象:会阻塞代码的运行,需等待 Promise 变为 resolved 状态返回结果后,才继续执行后续代码
(async function () {
    const p1 = new Promise(() => {}) 
    await p1 // p1 一直是一个 pending 状态的 Promise,代码将阻塞在这里,无限等待下去,后续的代码不会执行
    console.log('p1') // 此句不会执行
})()
  • await 后跟非 Promise 对象:会直接返回
(async function () {
    const res = await 100
    console.log(res) // 100
})()
  • await 相当于 Promise 的 then
(async function () {
    const p2 = Promise.resolve(100)
    const res = await p2 
    console.log(res) // 100
})()

(async function () {
    const res = await 100
    console.log(res) // 100
})()

(async function () {
    const p3 = Promise.reject('some err')
    const res = await p3 // p3 为rejected 状态的 Promise , 而 await 会一直等待 resolved 状态的 Promise,所以代码将阻塞在这里,无限等待下去,后续的代码不会执行
    console.log(res) // 不会执行
})()
  • 使用 try…catch 捕获异常,相当于 Promise 里 catch (有利于代码的标准化,因为异常标准的捕获方式就是使用 try…catch )
(async function () {
  const p4 = Promise.reject("some err");
  try {
    const res = await p4;
     console.log('await后的Promise执行成功后的返回值res:',res);
  } catch (err) {
    console.error('await后的Promise执行失败后的报错err:',err); 
  }
})();

在这里插入图片描述

async await 的本质

async await 只是语法糖,本质还是异步调用

  • await 之后的代码,都属于异步调用

下方代码的执行顺序,见代码注释的序号

async function async1 () {
  console.log('async1 start') //2
  await async2()
  console.log('async1 end') // 5 关键在这一步,它相当于放在 callback 中,最后执行
}

async function async2 () {
  console.log('async2')  //3
}

console.log('script start') // 1
async1()
console.log('script end') //4

执行结果

script start
async1 start
async2
script end
async1 end

async await 自测题

在这里插入图片描述
答案:a 是 Promise,b 是 100
解析:async 函数的返回值是 Promise , await 相当于 promise 的 then

在这里插入图片描述

答案: start 100 200

解析:

  • await 后接非Promise,不做处理,直接返回
  • await 相当于 promise 的 then 函数
  • resloved 状态的 promise 会触发 then 函数
  • rejected 状态的 promise 不会触发 then 函数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

朝阳39

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值