当前位置:首页 > 编程技术 > 正文内容

async + await 的理解和用法(Promise)

yc8881年前 (2022-12-14)编程技术221

1. 前言


async/await 是 ES7 提出的基于 Promise (ES6 中提出的) 的解决异步的最终方案

async + await 的作用: 简化 promise 的异步操作,把 promise 的异步操作编程变为同步的写法

async 将一个函数标记为异步函数,await 需要在异步函数中使用,标记当前操作是异步操作

async + await 必须配合 promise 使用,同时 async 和 await 必须一起使用。即 await 必须在 async 标记的函数中使用

2. 获取成功的结果


在 vue 脚手架和 uniapp 中经常使用的写法

  1. function getProfile() {
  2. return new Promise((resolve, reject) => {
  3. // 使用定时器模拟接口请求
  4. setTimeout(() => {
  5. resolve({
  6. code: 200,
  7. msg: "用户信息",
  8. data: {
  9. id: 1,
  10. name: "liang"
  11. }
  12. })
  13. }, 3000);
  14. });
  15. }
  16. // 以下代码会执行 输入 123 再执行输出 res
  17. function loadData() {
  18. getProfile().then(res => {
  19. console.log(res);
  20. })
  21. console.log(123);
  22. }
  23. // 下面写法会使 getProfile() 先执行
  24. // 等待三秒后执行完再把得到的结果赋值给左边的res,然后再继续往下执行
  25. async function loadData() {
  26. const res = await getProfile()
  27. console.log(res);
  28. console.log(123);
  29. }

3. 获取失败的结果


当 Promise 抛出错误信息时,控制台默认是直接抛出异常的

  1. reject('接口请求失败')

可以使用 try … catch 捕获 promise 抛出的错误

  1. try {
  2. const res = await getProfile()
  3. console.log(res);
  4. } catch (error) {
  5. console.log('error: ', error);
  6. }

4. 多个 Promise 的场景


使用 Promise

Promise.all 的参数是一个数组,数组的每一项是一个返回的 promise 的函数调用

  1. Promise.all([getProfile(), getProfile()]).then(res => {
  2. console.log(res, 'res');
  3. })

使用 await

因为 Promise.all 返回的也是一个 Promise,所以也可以使用 await

  1. async function loadData() {
  2. const res = await Promise.all([getProfile(), getProfile()])
  3. console.log(res);
  4. }

5. async 标记函数


使用 async 标记一个函数,那么当调用这个函数时,该函数会返回一个 promise 对象

如果没有在 async 函数中 return ,那么 promise 对象的 resolve 就是 undefined

如果在 async 函数中写了 return,那么 promise 对象的 resolve 就是 return 的值

如果 async 里的代码都是同步的,那么这个函数被调用就会同步执行

  1. async function fn(){
  2. console.log('a')
  3. }
  4. fn()
  5. console.log('b')
  6. //a
  7. //b

6. await 等待异步操作执行完成


右侧的表达式的结果就是 await 要等的东西,等到之后,对于 await 来说,分两个情况。是 promise 对象,不是 promise 对象

  1. const res = await getProfile()

如果不是 promise 对象,await 会阻塞后面的代码,先执行 async 外面的同步代码,再回到 async 内部,把这个非 promise 的东西,作为 await 表达式的结果

  1. function fn() {
  2. console.log(1)
  3. return 'this is return'
  4. }
  5. async function f1() {
  6. const res = await fn()
  7. console.log(2)
  8. console.log(res);
  9. }
  10. f1()
  11. console.log(3)
  12. //1
  13. //3
  14. //2
  15. // this is return

如果 await 等到的是一个 promise 对象,await 也会暂停 async 后面的代码,先执行 async 外面的同步代码,等着 Promise 对象 fulfilled,然后把 resolve 的参数作为 await 表达式的运算结果

  1. function fn() {
  2. console.log(1)
  3. return new Promise((resolve, reject) => {
  4. setTimeout(() => {
  5. resolve('this is return')
  6. }, 1500);
  7. });
  8. }
  9. async function f1() {
  10. const res = await fn()
  11. console.log(2)
  12. console.log(res);
  13. }
  14. f1()
  15. console.log(3)
  16. //1
  17. //3
  18. //2
  19. // this is return

6. async + await 相关文章推荐


async 和 await 【简书】: https://www.jianshu.com/p/b4fd76c61dc9

本站发布的内容若侵犯到您的权益,请邮件联系站长删除,我们将及时处理!


从您进入本站开始,已表示您已同意接受本站【免责声明】中的一切条款!


本站大部分下载资源收集于网络,不保证其完整性以及安全性,请下载后自行研究。


本站资源仅供学习和交流使用,版权归原作者所有,请勿商业运营、违法使用和传播!请在下载后24小时之内自觉删除。


若作商业用途,请购买正版,由于未及时购买和付费发生的侵权行为,使用者自行承担,概与本站无关。


本文链接:https://www.10zhan.com/biancheng/10224.html

标签: JavaScript
分享给朋友:

“async + await 的理解和用法(Promise)” 的相关文章

【说站】laravel实现自定义404页面并给页面传值

【说站】laravel实现自定义404页面并给页面传值

以 laravel5.8 为例,虽然有自带的404页面,但太简单,我们更希望能自定义404页面,将用户留在站点。实现的方式很简单,将自定义的视图文件命名为 404.blade.php,并放到 reso...

【说站】Thymeleaf报错Error resolving template “XXX”

【说站】Thymeleaf报错Error resolving template “XXX”

修改了一下开源项目的目录结构访问突然报错Error resolving template “XXX”可能原因有如下三种:第一种可能:原因:在使用springboot的过程中,如果使用thymeleaf...

【说站】Centos8.0如何配置静态IP详解及永久关闭防火墙

【说站】Centos8.0如何配置静态IP详解及永久关闭防火墙

这篇文章主要介绍了详解Centos8 配置静态IP的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来学习一下!1. 查看自己的网关地址点击虚...

【说站】电脑安装MySQL时出现starting the server失败原因及解决方案

【说站】电脑安装MySQL时出现starting the server失败原因及解决方案

今天在安装MySQL时出现starting the server失败,经过查询分析得出以下结论,记录一下操作步骤。原因分析:如果电脑是第一次安装MySQL,一般不会出现这样的报错。如下图所示。star...

【说站】vagrant实现linux虚拟机的安装并配置网络

【说站】vagrant实现linux虚拟机的安装并配置网络

一、VirtualBox的下载和安装1、下载VirtualBox官网下载:https://www.virtualbox.org/wiki/Downloads我的电脑是Windows的,所以下载Wind...

【说站】C#在PDF中添加墨迹注释Ink Annotation的步骤详解

【说站】C#在PDF中添加墨迹注释Ink Annotation的步骤详解

PDF中的墨迹注释(Ink Annotation),表现为徒手涂鸦式的形状;该类型的注释,可任意指定形状顶点的位置及个数,通过指定的顶点,程序将连接各点绘制成平滑的曲线。下面,通过C#程序代码介绍如何...