1.什么async/await
async和await是es8中引入的新语法,用来简化Promise的异步操作。在async和await出现之前,开发者只能通过链式.then()的方式处理Promise异步操作。示例代码如下:
1.1 .then()链式调用优点和缺点
-
优点
- 解决了回调地狱的问题
-
缺点
- 代码冗余,可读性差
- 不易理解
2. async/await的基本使用
如果某个方法的返回值是一个Promise实例对象,我们可以在它的调用的方法名前加await,最后这个方法返回值就不是Promise对象,而是一个具体的值,但是在 调用这个方法的外部函数需要加上async
import thenFs from "then-fs";
async function getFile(){
let r1= await thenFs.readFile("./studyAsyncAwait/files/1.txt","utf8");
console.log("r1:",r1);
let r2= await thenFs.readFile("./studyAsyncAwait/files/2.txt","utf8");
console.log("r2:",r2);
let r3= await thenFs.readFile("./studyAsyncAwait/files/3.txt","utf8");
console.log("r3:",r3);
}
getFile()
3. async/await的使用注意事项
- 如果function中使用了await,则function必须被async修饰
- 在async方法中,第一个await之前的代码会同步执行,await之后的代码会异步执行
import thenFs from "then-fs";
console.log("开始执行了");
async function getFile(){
console.log("开始执行了2");
let r1= await thenFs.readFile("./studyAsyncAwait/files/1.txt","utf8");
console.log("r1:",r1);
let r2= await thenFs.readFile("./studyAsyncAwait/files/2.txt","utf8");
console.log("r2:",r2);
let r3= await thenFs.readFile("./studyAsyncAwait/files/3.txt","utf8");
console.log("r3:",r3);
}
getFile()
console.log("结束");
执行结果:

4.总结

网友评论