当前位置: 首页 > news >正文

async/await 用法

1. 什么是 async/await

async/await ES8(ECMAScript 2017)引入的新语法,用来简化 Promise 异步操作。在 async/await 出 现之前,开发者只能通过链式 .then() 的方式处理 Promise 异步操作。示例代码如下:

import thenFs from 'then-fs'thenFs.readFile("./files/1.txt",'utf8') // 返回值是 promise 的实例对象。
.then(r1=>{   // 通过 .then 为第一个 Promise 实例指定成功之后的回调函数。console.log(r1)return thenFs.readFile("./files/2.txt",'utf8')  // 在第一个 .then 中返回一个新的 promise 的实例对象。
})
.then(r2=>{ // 继续调用 .then 为上一个 .then 的返回值(新的 Promise 实例) 指定成功之后的回调函数。console.log(r2)return thenFs.readFile("./files/3.txt",'utf8')  // 在第二个 .then 中返回一个新的 promise 的实例对象。
})
.then(r3=>{ // 继续调用 .then 为上一个 .then 的返回值(新的 Promise 实例) 指定成功之后的回调函数。console.log(r3)
})// 运行结果:
// txt file 1
// txt file 2
// txt file 3
  • .then 链式调用的优点: 解决了回调地狱的问题
  • .then 链式调用的缺点: 代码冗余、阅读性差、 不易理解 

 2. async/await 的基本使用

import thenFs from "then-fs";//按照顺序读取 1,2,3文件的内容
async function getAllFile(){const r1 = await thenFs.readFile("./files/1.txt",'utf8')// 当在 thenFs.readFile()方法前面添加 await 关键字时,返回的不是一个 Promise 实例了,而是文件的内容。console.log(r1)const r2 = await thenFs.readFile("./files/2.txt",'utf8')console.log(r2)const r3 = await thenFs.readFile("./files/3.txt",'utf8')console.log(r3)
}
//调用方法
getAllFile();// 运行结果:
// txt file 1
// txt file 2
// txt file 3

3. async/await 的使用注意事项

  1. 如果在 function 中使用了 await,则 function 必须被 async 修饰
  2. 在 async 方法中,第一个 await 之前的代码会同步执行,await 之后的代码会异步执行
import thenFs from "then-fs";console.log("A")
//按照顺序读取 1,2,3文件的内容
async function getAllFile(){console.log("B")const r1 = await thenFs.readFile("./files/1.txt",'utf8')const r2 = await thenFs.readFile("./files/2.txt",'utf8')const r3 = await thenFs.readFile("./files/3.txt",'utf8')console.log(r1,r2,r3)console.log("D")
}//调用方法
getAllFile();
console.log("C")// 运行结果:
// A
// B
// C
// txt file 1
// txt file 2
// txt file 3
// D
http://www.lryc.cn/news/38925.html

相关文章:

  • 好意外,发现永久免费使用的云服务器
  • VSCode使用技巧,代码编写效率提升2倍以上!
  • SQL执行过程详解
  • 【物联网NodeJs-5天学习】第四天存储篇⑤ ——PM2,node.js应用进程管理器
  • 【C++学习】【STL】deque容器
  • 当 App 有了系统权限,真的可以为所欲为?
  • vue3.js的介绍
  • 【Three.js】shader特效 能量盾
  • 【6000字长文】需求评审总是被怼?强烈推荐你试试这三招
  • Hive介绍及DDL
  • Simulink 自动代码生成电机控制:在某国产ARM0定点MCU上实现自动代码生成无感电机控制
  • MySQL基本查询
  • 你需要知道的 7 个 Vue3 技巧
  • 行政区划获取
  • 让ChatGPT介绍一下ChatGPT
  • 【Redis】Redis 主从复制 + 读写分离
  • 2023届秋招,鬼知道我经历了什么
  • ChatGPT助力校招----面试问题分享(一)
  • CSS媒体查询@media (prefers-color-scheme:dark)判断系统白天黑夜模式
  • 运行YOLOv8实现识别
  • 如何在Linux中优雅的使用 head 命令,用来看日志简直溜的不行
  • Nginx.conf 配置详解
  • 剖析NLP历史,看chatGPT的发展
  • 20个Python使用小技巧,建议收藏~
  • Kafka 主题管理
  • 【深度学习】GPT系列模型:语言理解能力的革新
  • 【Vue.js】全局状态管理模式插件vuex
  • JPA 之 Hibernate EntityManager 使用指南
  • 英语作文提示(持续更新)
  • 【计算机组成原理】计算机的性能指标、数据的表示和运算、BCD码和余3码