async await基础

382 阅读1分钟

一、async await是什么

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

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

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

二、 有什么特点

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

async

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

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

await

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

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

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

async function getUserData() {
		let 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;
}