What is async await

It’s a way to handle asynchrony, and it’s much cleaner than promise.

Async means to declare an asynchronous function and await the result returned by the asynchronous function with the await keyword.

Async function getUserData() {let response = await fetch('/ API /user')}Copy the code

Two, what are the characteristics

Written to read like synchronous code, it is easier to understand.

async

Async is added, and its return value is wrapped as a Promise object

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

await

Accept the promise and convert the result to either a return value or an exception.

Important rule: Use the await keyword only inside functions declared with the async keyword.

Await blocks code inside async after it.

Async function getUserData() {let response = await fetch('/ API /user') // Console will wait until await receives the promise result console.log('next-line') }Copy the code

3. Business scenarios

You need to wait for the return value of an asynchronous operation before performing other operations.

Like waiting for retrieveUsers to get the results. Set loading to false


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

4. Advantages of async await over Promise

The most obvious is to write more succinctly, synchronous style code

// 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));
}
Copy the code

5. Disadvantages of async await

If used in a method that does not have dependencies, request time is wasted

Async function test() {const listA= await getA(); const listA= await getA(); const listB = await getB(); }Copy the code

To improve the

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