Js Async And Await in JavaScript
? JavaScript Async & Await
What are async and await?
Modern way to write asynchronous code in JavaScript.
Makes asynchronous code look and behave like synchronous code.
Built on top of Promises.
async Function
Declaring a function with
asyncmeans it always returns a Promise.Inside an async function, you can use
awaitto wait for promises.
async function fetchData() { return "Data received";}fetchData().then(data => console.log(data)); // Logs: Data receivedawait Keyword
Can only be used inside an async function.
Pauses execution until the promise resolves.
Makes code easier to read than chaining
.then().
async function getData() { let promise = new Promise((resolve) => { setTimeout(() => resolve("Done!"), 1000); }); let result = await promise; // Wait here until promise resolves console.log(result);}getData(); // Logs "Done!" after 1 secondExample: Fetch API with Async/Await
async function fetchUser() { try { const response = await fetch("https://jsonplaceholder.typicode.com/users/1"); const user = await response.json(); console.log(user.name); } catch (error) { console.error("Error:", error); }}fetchUser();Benefits
Cleaner and more readable asynchronous code.
Easier error handling with
try/catch.Avoids “callback hell” and
.then()chains.
Important Notes
awaitpauses the async function without blocking the whole program.Use
try/catchto handle errors inside async functions.
Want me to show you how async/await compares to Promises or callbacks, or how to handle multiple async calls?