When working with APIs or other asynchronous operations in JavaScript, you'll often use async and await.
They make asynchronous code easier to read and understand.
async
The async keyword makes a function return a Promise.
async function getMessage() {
return "Hello World";
}
Because it's an async function, the result is a Promise.
await
await waits for a Promise to finish before continuing.
async function getData() {
const response = await fetch("https://api.example.com/users");
const data = await response.json();
console.log(data);
}
Instead of writing:
fetch(url)
.then(response => response.json())
.then(data => console.log(data));
we can use async/await, which is usually easier to read.
Error handling
Use try...catch to handle errors:
async function getData() {
try {
const response = await fetch(url);
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
Simple rule to remember
async → makes a function return a Promise
await → waits for a Promise
try/catch → handles errors
That's the basic idea behind async and await in JavaScript.
Top comments (0)