简介

async和await是JavaScript的语法,具体详细介绍可以看阮一峰的教程async 函数
这里我只是介绍在日常开发中,async和await的常见用法。

  • async:异步函数,返回的是一个Promise对象,可以使用then方法添加回调函数。
  • await:对紧跟在await后面的表达式,需要等待它的结果,其完成后再接着执行后面的语句。
  • await关键字只能放在async函数里,await配合async一起使用

async

定义一个异步方法很简单,在函数前边加上 async 关键字即可。

<template>
  <el-button @click="buttonClick">我是按钮</el-button>
</template>

<script setup lang="ts">
//用async定义一个异步函数
async function sayHello(num: string) {
  return "Hello,亚瑟王" + num
}

function buttonClick() {
  sayHello("1").then(result => {
    console.log(result)
  })
  console.log("虽然我在后边,但是我先执行")
}
</script>

运行结果:
在这里插入图片描述
可以看到sayHello()的返回值是后打印出的,因为它是异步方法。

await

await 会让它后面的表达式变成同步,当该表达式执行完成后,才会继续执行下面的代码。
对上面的buttonClick()进行修改:

  • function buttonClick()的前面加上async
  • sayHello的前面加上await
  • 修改最后打印的中文
async function buttonClick() {
  await sayHello("1").then(result => {
    console.log(result)
    return result
  });
  console.log("虽然我在后边,但是我先执行,是真的吗?")
}

运行结果:
在这里插入图片描述
可以看出sayHello()先执行完成,在执行最后一句console.log()的。

案例:在for循环中调用异步函数

  • 重要的注意点:循环调用异步函数,要用for,不能用forEach
  • listByDictTypeCode()是一个异步函数,根据code调用后端接口,返回字典数据

1 不使用async和await

function myFunction() {
  const dictMap = getDictMap();
  console.log("aa的值 = " + dictMap.get("aa"))
}

function getDictMap() {
  const dictMap = new Map<string, DictDatas[]>();
  let codes = ['aa', 'bb', 'cc'];
  
  for (const code of codes) {
     listByDictTypeCode(code).then(resp => {
      dictMap.set(code, resp.data);
    })
  }
  console.log("已经返回" + dictMap.size + "条");
  return dictMap;
}

运行结果:
在这里插入图片描述
虽然listByDictTypeCode()确实执行了,但是最后的return dictMap在listByDictTypeCode()执行完成之前就已经返回了,所以myFunction()里没有获取到字典值。

2 使用async和await来解决

function myFunction() {
  const dictMap = getDictMap();
  dictMap.then(result => {
    console.log("aa的值 = " + result.get("aa"))
  })
}

async function getDictMap() {
  const dictMap = new Map<string, DictDatas[]>();
  let codes = ['aa', 'bb', 'cc'];

  for (const code of codes) {
    await listByDictTypeCode(code).then(resp => {
      dictMap.set(code, resp.data);
    })
  }
  console.log("已经返回" + dictMap.size + "条");
  return dictMap;
}

运行结果:
在这里插入图片描述
从结果可以看到,是等待listByDictTypeCode()都执行完成后,再return dictMap的。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐