async Functions
The async keyword turns any function into one that returns a Promise. Inside, you can use await to pause execution until a promise settles.
async function getData() {
return "Data loaded";
}
getData().then(msg => console.log(msg));
Try it Yourself โ
Using await
await pauses the async function until the promise resolves. It makes asynchronous code read like synchronous code.
async function fetchUser(id) {
const response = await fetch("https://api.example.com/users/" + id);
const user = await response.json();
console.log(user.name);
}
fetchUser(1);
Try it Yourself โ
Error Handling
Wrap await calls in try...catch to handle promise rejections gracefully.
async function loadData() {
try {
const result = await fetch("https://api.example.com/bad-url");
console.log(await result.json());
} catch (error) {
console.error("Failed to load:", error.message);
}
}
loadData();
Try it Yourself โ