In JavaScript,
async and
await are keywords that work together to simplify asynchronous programming and provide a more synchronous-style code structure while still utilizing promises.
1. `async`: The `async` keyword is used to declare an asynchronous function. It can be placed before a function declaration, function expression, or method definition. When a function is marked as `async`, it always returns a
promise, allowing the use of `await` within it.
Here's an example of an `async` function declaration:
async function fetchData() {
// Asynchronous operations
}
And an `async` function expression:
const fetchData = async function() {
// Asynchronous operations
};
2. `await`: The `await` keyword is used inside an `async` function to pause the execution and wait for a promise to be resolved or rejected. It can only be used within an `async` function.
The `await` keyword is followed by a promise. If the promise is resolved, the value it resolves with is returned. If the promise is rejected, an error is thrown, which can be caught using `try/catch` blocks.
Here's an example of using `await` to wait for a promise to resolve:
async function fetchData() {
const data = await fetch('https://api.example.com/data');
console.log(data); // Access the resolved value
}
In this example, the `fetchData` function pauses at the `await` expression until the `fetch` function's promise resolves with the fetched data. The resolved value is then stored in the `data` variable.
It's important to note that the use of `await` can only be done within an `async` function, so the calling function or code block must also be marked as `async` if it wants to use `await`.
`async/await` provides a more sequential and readable way of handling asynchronous operations compared to using callbacks or chaining promises with `.then()`. It eliminates the need for excessive nesting or complex chaining and allows for more structured error handling using `try/catch` blocks.
It's worth mentioning that `async/await` is built on top of promises, so it's still important to understand promises and how they work in JavaScript.