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的使用注意事项:
- 如果在function中使用了await,则这个function必须被async修饰
- 在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