发布时间:2025-02-02 15:01
async/await 是 ES8(ECMAScript 2017)引入的新语法,用来简化 Promise 异步操作。在 async/await 出
现之前,开发者只能通过链式 .then() 的方式处理 Promise 异步操作。示例代码如下:
import thenFs from 'then-fs' thenFs .readFile('./files/11.txt', 'utf8') .catch((err) => { console.log(err.message) }) .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 链式调用的缺点:代码冗余、阅读性差、不易理解。
使用 async/await 简化 Promise 异步操作的示例代码如下:
import thenFs from 'then-fs' 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()
① 如果在 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') 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) console.log('D') } getAllFile() console.log('C') //打印出来的结果为 A B C 111 222 222 D