async and await
are features introduced in ECMAScript 2017 (ES8) to simplify working with asynchronous code in JavaScript. They make it easier to work with promises and perform asynchronous operations in a more readable and synchronous-like manner.
async
Function:
The async
keyword is used to declare a function as asynchronous. An asynchronous function returns a promise implicitly, and its body will contain asynchronous operations.
Example:
async function fetchData() {
// Asynchronous operation, e.g., fetching data from a server
const response = await fetch('https://api.example.com/data');
const data = await response.json();
// Rest of the code to work with the data
console.log(data);
}
// Call the async function
fetchData();
await
Keyword:
The await
keyword can only be used inside an async
function. It is used to wait for a promise to resolve or reject before moving on to the next line of code. This makes asynchronous code look and behave more like synchronous code.
In the example above, await fetch('https://api.example.com/data')
waits for the fetch
operation to complete and returns the result (a response object). Similarly, await response.json()
waits for the parsing of the JSON data.
Handling Errors:
Async functions allow you to use try...catch
blocks to handle errors in a more synchronous-looking style.
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
Returning Promises:
Async functions always return a promise. If a value is explicitly returned from the function, it will be wrapped in a resolved promise.
async function example() {
return 'Hello, Async/Await!'; // Equivalent to returning Promise.resolve('Hello, Async/Await!')
}
example().then(result => console.log(result)); // Logs: Hello, Async/Await!
These features help make asynchronous code more readable and maintainable by avoiding the callback hell associated with nested callbacks. It's important to note that async/await
is built on top of promises and does not replace them but rather provides a more convenient syntax for working with them.