关于async/await

10 篇文章 0 订阅

1.什么是 async/await

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

链式.then()方法 虽然解决了回调地狱的问题,但是代码冗余,阅读性差,不易理解

2. async/await 的基本使用

import thenFs from "then-fs";

async function getAllFile() {
  // async 和 await 是成对出现的,方法内部用了await,则这个方法要用async修饰
  const r1 = await thenFs.readFile('./files/a.txt','utf8')
  console.log(r1);
  const r2 = await thenFs.readFile('./files/b.txt','utf8')
  console.log(r2);
  const r3 = await thenFs.readFile('./files/c.txt','utf8')
  console.log(r3);
}

getAllFile() // 按顺序打印出 aaa bbb ccc

2.1 async/await的使用注意事项:

  1. 如果在function中使用了await,则这个function必须被async修饰
  2. 在async 方法中,第一个await之前的代码会同步执行,await之后的代码会异步执行

举例如下:

import thenFs from "then-fs";

console.log('A');// 1. 主线程先输出 A
async function getAllFile() {
  console.log('B'); // 3. 同步输出B
	// 4.碰到第一个await,则后面的代码都会异步执行,于是主线程退出getAllFile()的执行
  const r1 = await thenFs.readFile('./files/a.txt','utf8')
  const r2 = await thenFs.readFile('./files/b.txt','utf8')
  const r3 = await thenFs.readFile('./files/c.txt','utf8')
  console.log(r1,r2,r3); // 6. 读取3个文件
  console.log('D'); // 7. 输出D
}

getAllFile() //2. 主线程执行该方法

console.log('C'); // 5. 输出C

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值