What is async?
async is a keyword used before a function to make it always return a promise.
Example:
async function greet() {
return "Hello!";
}
greet().then(msg => console.log(msg)); // Output: Hello!
What is await?
await pauses the execution of an async function until a promise resolves.
Example:
async function fetchData() {
let promise = new Promise((resolve) => {
setTimeout(() => resolve("Data received!"), 2000);
});
let result = await promise;
console.log(result); // Output after 2s: Data received!
}
fetchData();
How async and await Work Together
Show how they make asynchronous code** look synchronous.**
Compare code written with .then() vs with async/await.
Error Handling with try...catch
Example:
async function getData() {
try {
let res = await fetch("https://jsonplaceholder.typicode.com/posts/1");
let data = await res.json();
console.log(data);
} catch (error) {
console.log("Error:", error);
}
}
getData();
When to Use async/await
- When working with API calls (fetch, Axios).
- When you want cleaner code instead of .then() chains.
- When error handling is important.
Top comments (0)