小言_互联网的博客

async/await

336人阅读  评论(0)

1. 什么是 async/await

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

import thenFs from "then-fs";

thenFs.readFile('./files/1.txt', 'utf8')
    .then(r1 => {
   
        console.log(r1);
        return thenFs.readFile('./files/2.txt', 'utf8')

    })
    .then(r2 => {
   
        console.log(r2);
        return thenFs.readFile('./files/3.txt', 'utf8')

    })
    .then(r3 => {
   
        console.log(r3);
    })

 

.then 链式调用的优点:解决了回调地狱的问题
.then 链式调用的缺点:代码冗余、阅读性差、不易理解

2. async/await 的基本使用

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

import thenFs from "then-fs";

// 按照顺序读取文件 1,2,3 的内容
async function getAllFile() {
   
    const r1 = await thenFs.readFile('./files/1.txt', 'utf8')
    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()

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

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

import thenFs from "then-fs";

console.log("A");
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");


 


转载:https://blog.csdn.net/qq_41050821/article/details/128740638
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场