async await
时间: 2023-09-01 21:11:40 浏览: 80
Async/await is a feature in modern JavaScript that allows developers to write asynchronous code in a synchronous style. The async keyword is used to define a function that returns a promise, while the await keyword is used to wait for the resolution of a promise.
Async/await is a more readable and easier-to-understand way to write asynchronous code than using callbacks or promises. It allows developers to write code that looks like regular synchronous code, making it easier to reason about and debug.
Here's an example of using async/await to fetch data from an API:
```
async function fetchData() {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
console.log(data);
}
fetchData();
```
In this example, the fetchData function is declared as async and returns a promise. Inside the function, we use the await keyword to wait for the fetch request to complete and the response to be returned. Once we have the response, we use another await keyword to wait for the response to be parsed as JSON. Finally, we log the data to the console.
Async/await is a powerful tool for writing asynchronous code and is widely used in modern JavaScript applications.
阅读全文