ES6----async/await

简介: ES6----async/await

什么是async/await

async/await 是 ES8(ECMAScript 2017) 引入的新语法,用来简化Promise异步操作。在 async/await 出

现之前,开发者只能通过链式 .then() 的方式处理Promise异步操作。示例代码如下:

import thenFs from 'then-fs'
thenFs.readFile( './1.txt', 'utf-8' ).then(
  result => {
    console.log(result)
    return thenFs.readFile( './2.txt', 'utf-8' )
  }
).then(
  result => {
    console.log(result)
    return thenFs.readFile( './3.txt', 'utf-8' )
  }
).then(
  result => {
    console.log(result)
  }
)

.then 链式调用的优点:解决了回调地狱的问题。

.then链式调用的缺点:代码冗余、阅读性差、不易理解。

async/await的基本使用

使用async/await简化Promise异步操作的实例代码:

import thenFs from 'then-fs'
// 按照顺序读取文件
async function getAllFile() {
  const r1 = await thenFs.readFile( './1.txt', 'utf8' )
  console.log(r1)
  const r2 = await thenFs.readFile( './2.txt', 'utf8' )
  console.log(r2)
  const r3 = await thenFs.readFile( './3.txt', 'utf8' )
  console.log(r3)
}
getAllFile()
11111
22222
3333333

使用async/await,读取文件的返回结果为文件的内容。

async/await的使用注意事项

1.如果在function中使用了await,则 function必须被async修饰。

2.在 async方法中,第一个await之前的代码会同步执行,await之后的代码会异步执行。

同步任务全部执行完成后才执行异步任务。

示例:

求输出的顺序

import thenFs from "then-fs"
console.log('A') //同步任务
async function getAllFile() {
  console.log( 'B') //同步任务
  //接下去为异步任务
  //会先退出,执行后面的同步任务
  const r1 = await thenFs.readFile( './1.txt' , 'utf8')
  const r2 = await thenFs.readFile( './2.txt' , 'utf8')
  const r3 = await thenFs.readFile( './3.txt' , 'utf8')
  //异步任务按进入执行队列的顺序输出
  console.log(r1,r2,r3)
  console.log( 'D')
}
getAllFile()
console.log( 'C')//同步任务
A
B
C
11111 22222 3333333
D

相关文章
|
人工智能 数据安全/隐私保护
AI Agent是大模型落地业务场景的主流形式
【1月更文挑战第5天】AI Agent是大模型落地业务场景的主流形式
578 2
AI Agent是大模型落地业务场景的主流形式
|
SQL 分布式计算 DataWorks
dataworks学习
【9月更文挑战】
418 5
|
消息中间件 运维 Java
实现分布式事务处理的Java解决方案
实现分布式事务处理的Java解决方案
|
PyTorch TensorFlow 算法框架/工具
手把手教你-MAC笔记本安装Pytorch环境
手把手教你-MAC笔记本安装Pytorch环境
|
缓存 安全 Cloud Native
Nginx配置最佳实践
Nginx配置最佳实践
436 0
Element UI 多选表格--判断勾选数据行的 Checkbox 时为选中还是取消选中
Element UI 多选表格--判断勾选数据行的 Checkbox 时为选中还是取消选中
473 1
|
SQL HIVE
Hive 行列转换
使用`lateral view + explode`或`inline`可将列转换为行,实现数据降维。例如,`explode(array|map)`用于单列转多行,`inline(array_struct)`将结构体数组拆分成多行。同样,通过条件聚合可实现行转列,常用于多行数据聚合到单行中,如示例所示的按月统计订单金额。
471 1
Hive 行列转换
|
小程序 JavaScript Java
基于SpringBoot+Vue+uniapp微信小程序的小说阅读器的详细设计和实现
基于SpringBoot+Vue+uniapp微信小程序的小说阅读器的详细设计和实现
294 2
|
机器学习/深度学习 数据采集 人工智能
「AIGC」Stable Diffusion教程详解
**Stable Diffusion教程摘要:** Stable Diffusion是AI绘画工具,利用GAN学习艺术家风格。基础教程涵盖软件介绍、配置需求(NVIDIA GPU、Windows 10/11)、安装及基础操作,如模型切换、VAE使用、采样步数调整等。AI作画原理涉及U-net、Diffusion模型、文本映射(如CLIP)和条件生成。Stable Diffusion运用Latent Diffusion Model从潜在空间生成高清图像,开源且在艺术创作中广泛应用。
538 0