async/await 是 ES8(ECMAScript 2017)引入的新语法,用来简化 Promise 异步操作。在 async/await 出 现之前,开发者只能通过链式 .then() 的方式处理 Promise 异步操作。示例代码如下:
import thenFs from 'then-fs'thenFs.readFile("./files/1.txt",'utf8') // 返回值是 promise 的实例对象。
.then(r1=>{ // 通过 .then 为第一个 Promise 实例指定成功之后的回调函数。console.log(r1)return thenFs.readFile("./files/2.txt",'utf8') // 在第一个 .then 中返回一个新的 promise 的实例对象。
})
.then(r2=>{ // 继续调用 .then 为上一个 .then 的返回值(新的 Promise 实例) 指定成功之后的回调函数。console.log(r2)return thenFs.readFile("./files/3.txt",'utf8') // 在第二个 .then 中返回一个新的 promise 的实例对象。
})
.then(r3=>{ // 继续调用 .then 为上一个 .then 的返回值(新的 Promise 实例) 指定成功之后的回调函数。console.log(r3)
})// 运行结果:
// txt file 1
// txt file 2
// txt file 3
import thenFs from "then-fs";//按照顺序读取 1,2,3文件的内容
async function getAllFile(){const r1 = await thenFs.readFile("./files/1.txt",'utf8')// 当在 thenFs.readFile()方法前面添加 await 关键字时,返回的不是一个 Promise 实例了,而是文件的内容。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();// 运行结果:
// txt file 1
// txt file 2
// txt file 3
import thenFs from "then-fs";console.log("A")
//按照顺序读取 1,2,3文件的内容
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")// 运行结果:
// A
// B
// C
// txt file 1
// txt file 2
// txt file 3
// D