promise、async await
时间: 2023-09-28 17:07:37 浏览: 111
js--promise、async 和 await 相关知识总结.doc
`Promise` is a built-in JavaScript object that represents a value that may not be available yet but will be resolved in the future. It is commonly used for asynchronous operations, such as fetching data from a server or reading a file from disk. Promises have three states: pending, resolved, or rejected.
`async/await` is a syntax for working with Promises that was introduced in ECMAScript 2017. The `async` keyword is used to define an asynchronous function that returns a Promise. The `await` keyword is used to pause the execution of the function until a Promise is resolved. This allows for more readable and concise code when working with asynchronous operations.
Here is an example of using Promise and async/await:
Promise:
```
fetch('https://example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
```
async/await:
```
async function fetchData() {
try {
const response = await fetch('https://example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
fetchData();
```
阅读全文