Detailed explanation of async and await in js

introduction

JavaScript is an event-driven and asynchronous programming language, and asynchronous programming is one of the most commonly used programming methods in JavaScript. In asynchronous programming, we usually use callback functions or Promise objects to handle the results of asynchronous operations. In ES2017, the async and await keywords were introduced to make asynchronous programming more concise and readable.

Promise object

Before introducing async and await, let's first understand Promisethe object. PromiseObject is a mechanism for handling asynchronous programming in JavaScript. It can encapsulate asynchronous operations into an object, so that the results of asynchronous operations can be processed like synchronous operations.

A Promiseobject represents the eventual completion or failure of an asynchronous operation and can return its result to the caller of the asynchronous operation. Promise Objects have three states: pending(waiting), fulfilled(completed), and rejected(failed). When an Promise object is in the waiting state, it indicates that the asynchronous operation is in progress; when a Promise object is in the completed state, it indicates that the asynchronous operation has completed successfully; when an Promiseobject is in the failed state, it indicates that the asynchronous operation has failed .

When working with Promiseobjects, we usually use thenthe method to handle the result of an asynchronous operation, or catchthe method to handle the error of an asynchronous operation. Here is a simple example showing how to use Promise objects to handle the results of asynchronous operations:

javascript
Copy code
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

In the above example, we use fetchthe function to fetch data from the server and parse it into JSONthe format. We then use thenthe method to handle the parsed data, or catchthe method to handle errors.

async function

asyncA function is a special kind of function that returns an Promiseobject. A function declared with asyncthe keyword can internally use awaitthe keyword to wait for an asynchronous operation to complete, returning a Promiseobject. async Using the keyword in a function allows awaitthe result of an asynchronous operation to be processed like a synchronous operation, thus avoiding the problem of callback hell.

Here is a simple example showing how to define and call asynca function:

javascript
Copy code
// 定义一个 async 函数
async function getData() {
    
    
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}

// 调用 async 函数
getData()
  .then(data => {
    
    
    console.log(data);
  })
  .catch(error => {
    
    
    console.error(error);
  });

In the example above, we first defined a function getDatacalled async. In getDatathe function, we use awaitthe keyword to wait for the completion of the asynchronous operation fetching data from the server and parse the result into JSONthe format. Finally, getDatathe function returns the parsed data.

When calling getDatathe function, we use thenthe method to handle the returned data, or catchthe method to handle errors. Since the getData function returns an Promiseobject, we can use Promisethe standard method of to process the returned result.

It should be noted that awaitkeywords can only asyncbe used in functions, otherwise it will cause syntax errors. If the keyword async is used in a non-function await , it will cause a syntax error.

await keyword

The await keyword is used to wait for an asynchronous operation to complete and return the result of the asynchronous operation. When using await, it needs to be placed asyncinside a function. While waiting for the asynchronous operation to complete, JavaScriptthe engine suspends execution of the current function and waits for the asynchronous operation to complete before continuing with the code below.

Here is a simple example showing how to use await:

javascript
Copy code
async function fetchData() {
    
    
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}

// 调用 fetchData 函数
fetchData().then(data => {
    
    
  console.log(data);
}).catch(error => {
    
    
  console.error(error);
});

In the example above, fetchDatathe function uses await wait for fetchthe result returned by the function, and then waits for the result to be parsed into JSONthe format. Finally, fetchDatathe function returns the parsed data. When calling fetchDatathe function, use thenthe method to handle the returned data, or catch the method to handle errors.

It should be noted that awaityou can only wait for Promisethe completion of the asynchronous function that returns the object, if the object you are waiting for is not Promisean object, it will be automatically converted to Promisean object.

Summarize

asyncand awaitare JavaScripta new way to handle asynchronous programming in , they allow the results of asynchronous operations to be processed like synchronous operations, making asynchronous programming more concise and readable. When using asyncand await, you need to pay attention to the following points:

  • asyncThe return value of the function is an Promiseobject;
  • await Keywords can only asyncbe used in functions;
  • awaitThe keyword can only wait for the execution of the asynchronous function returning Promisethe object to complete;
  • When used await, JavaScriptthe engine suspends execution of the current function until the asynchronous operation completes.

Guess you like

Origin blog.csdn.net/weixin_45629285/article/details/130925510