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 Promise
the object. Promise
Object 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 Promise
object 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 Promise
object is in the failed state, it indicates that the asynchronous operation has failed .
When working with Promise
objects, we usually use then
the method to handle the result of an asynchronous operation, or catch
the 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 fetch
the function to fetch data from the server and parse it into JSON
the format. We then use then
the method to handle the parsed data, or catch
the method to handle errors.
async function
async
A function is a special kind of function that returns an Promise
object. A function declared with async
the keyword can internally use await
the keyword to wait for an asynchronous operation to complete, returning a Promise
object. async
Using the keyword in a function allows await
the 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 async
a 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 getData
called async
. In getData
the function, we use await
the keyword to wait for the completion of the asynchronous operation fetching data from the server and parse the result into JSON
the format. Finally, getData
the function returns the parsed data.
When calling getData
the function, we use then
the method to handle the returned data, or catch
the method to handle errors. Since the getData function returns an Promise
object, we can use Promise
the standard method of to process the returned result.
It should be noted that await
keywords can only async
be 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 async
inside a function. While waiting for the asynchronous operation to complete, JavaScript
the 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, fetchData
the function uses await
wait for fetch
the result returned by the function, and then waits for the result to be parsed into JSON
the format. Finally, fetchData
the function returns the parsed data. When calling fetchData
the function, use then
the method to handle the returned data, or catch
the method to handle errors.
It should be noted that await
you can only wait for Promise
the completion of the asynchronous function that returns the object, if the object you are waiting for is not Promise
an object, it will be automatically converted to Promise
an object.
Summarize
async
and await
are JavaScript
a 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 async
and await
, you need to pay attention to the following points:
async
The return value of the function is anPromise
object;await
Keywords can onlyasync
be used in functions;await
The keyword can only wait for the execution of the asynchronous function returningPromise
the object to complete;- When used
await
,JavaScript
the engine suspends execution of the current function until the asynchronous operation completes.