前端中async和await

async和await是ES8引入的新语法,用来简化Promise异步操作

用来修饰返回Promise对象的函数

1
2
3
4
5
6
7
// 当函数中出现await,则函数必须用async修饰
async function getAllFile() {
// 返回Promise对象
const r2 = thenFs.readFile('code1/files/1.txt', 'utf8')
// 直接返回内容对象
const r2 = await thenFs.readFile('code1/files/1.txt', 'utf8')
}
  • 执行顺序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// A B C r1 r2 r3 D
console.log('A')
async function getAllFile() {
console.log('B')
const r1 = await thenFs.readFile('code1/files/1.txt', 'utf8')
console.log(r1)
const r2 = await thenFs.readFile('code1/files/2.txt', 'utf8')
console.log(r2)
const r3 = await thenFs.readFile('code1/files/3.txt', 'utf8')
console.log(r3)
console.log('D')
}

getAllFile()
console.log('C')
赏个🍗吧
0%