What is async/await in JavaScript with example?
async/await
is a way to handle asynchronous code in JavaScript, and it is built on top of Promises. It makes working with asynchronous code look like working with synchronous code, making it easier to understand and write.
Here’s an example:
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
fetchData()
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
In this example, the fetchData
function returns a Promise that resolves with the data obtained from the API. The await
keyword is used to wait for the fetch
function to complete and for the response.json()
method to resolve.
The async
keyword is used to indicate that a function returns a Promise and can be await
-ed.
This makes the code look more like synchronous code and eliminates the need for chaining multiple .then
functions.