【async/await】黑马vue视频笔记(十二)

1. 什么是 async/await

async/await 是 ES8(ECMAScript 2017)引入的新语法,用来简化 Promise 异步操作。在 async/await 出现之前,开发者只能通过链式 .then() 的方式处理 Promise 异步操作。

import thenFs from 'then-fs'
thenFs.readFile('./file/1.txt', 'utf8') // 1. 返回值是Promise的实例对象
	.then((r1) => { // 2. 通过 .then为第一个Promise实例指定成功之后的回调函数
		console.log(r1)
		return thenFs.readFile('./file/2.txt','utf8') //3. 在第一个.then 中返回一个新的Promise实例对象
	})
	.then((r2) => { // 4. 继续调用 .then 为上一个 .then 的返回值(新的Promise实例)指定成功之后的回调函数
		console.log(r2)
		return thenFs.readFile('./file/3.txt','utf8') // 5. 在第二个 .then中返回一个新的Promise实例对象
	})
	.then((r3) => { // 6. 继续调用 .then 为上一个 .then的返回值(新的Promise)实例指定成功之后的回调函数
		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('./file/1.txt', 'utf8')
	console.log(r1)
	const r2 = await thenFs.readFile('./file/2.txt', 'utf8')
	console.log(r2)
	const r3 = await thenFs.readFile('./file/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('./file/1.txt','utf8')
	const r2 = await thenFs.readFile('./file/2.txt','utf8')
	const r3 = await thenFs.readFile('./file/3.txt', 'utf8')
	console.log(r1, r2, r3)
	console.log('D')
}

getAllFile()
console.log('C')
// A
// B
// C
// 111 222 333
// D
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值