async await

一、async await是什么

是处理异步的一种方式,比起promise写法更加简洁。

async 表示声明一个异步函数,内部用await关键字等待这个异步函数返回的结果。

基本写法:
async getUserData() {
	this.response = await fetch('/api/user')
}

二、 有什么特点

写法上读起来像同步代码,因此更好理解。

async

函数加了async, 它的返回值会被包装成promise对象

async fn () {
	return 'aab'
}
console.log(f1())  
//Promise {<fulfilled>: 'aab'}

await

接收promise并把结果转换为返回值或者一个异常。

重要规则:只能在以async关键字声明的函数内部使用await关键字。

await会阻塞async函数内部在它之后的代码。

   async getUserData () {
      this.response = await fetch('/api/user')
      // 会等到await接收到promise结果之后在执行console
      console.log('next-line')
    }

三、业务场景

需要等待某个异步操作的返回值,再进行其他操作;

比如等retrieveUsers得到结果。再去把loading设为false

async getUsersList() {
        await this.retrieveUsers({
          factoryId: this.factoryId,
          workshopId: this.currentWorkshopId,
          userRole: this.currentUserRole
        })
        this.isLoading = false
      },

四、比起Promise,async await写法的优势

最明显的就是写法更简洁,是同步风格的代码

// async/await //不用担心回调地狱的发生
async getBooks(authorId) {
  const books = await fetchAllBooks();
  return books.filter(b => b.authorId === authorId);
}
// promise 可能会造成回调地狱
getBooksWithPromise(authorId) {
  return fetchAllBooks()
    .then(books => books.filter(b => b.authorId === authorId));
}

五、async await写法的缺点

如果用在不存在依赖关系的方法中,会浪费请求时间

async function test() {
  // 这么写,如果两个方法不存在依赖关系,getB会在getA之后才执行,请求的时间会变多
	const listA= await getA();
  const listB = await getB();
}

改进

async function test() {
	const listPromise = getList();
  const anotherListPromise = getAnotherList();
  await listPromise;
  await anotherListPromise;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值