Async/Await Concept in Javascript/LWC

 

Concept of async and await in JavaScript

async and await are used in asynchronous programming in JavaScript. They help us write cleaner, more readable, and more manageable asynchronous code without using complex callback functions or Promise chains.


🔸 Why Do We Need async/await?

JavaScript is single-threaded, meaning it executes one operation at a time. However, sometimes we need to perform long-running tasks like:

  • Fetching data from a server (API calls)
  • Reading files
  • Accessing databases
  • Waiting for user input

If JavaScript waits for each task to complete before moving to the next, the app becomes slow and unresponsive. To avoid this, we use asynchronous programming.


🔹 async Function

An async function always returns a Promise. This means the function runs in the background and does not block the execution of other code.

🔹 Example:

javascript

async function fetchData() { return "Hello, World!"; } fetchData().then(response => console.log(response)); // Output: Hello, World!

Here, fetchData() returns a Promise that resolves to "Hello, World!".


🔹 await Keyword

The await keyword pauses the execution of an async function until a Promise is resolved.

🔹 Example:

javascript

async function fetchData() { let response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); let data = await response.json(); console.log(data); } fetchData();

What Happens Here?

  1. fetch() returns a Promise, which is awaited.
  2. await response.json() waits for the JSON data.
  3. console.log(data) runs only after the data is available.

🚀 Without await, JavaScript would move to the next line before fetch() completes, leading to undefined or incomplete data.


🔸 Key Benefits of async/await

Code looks synchronous & easy to read
Avoids callback hell (nested callbacks)
Better error handling with try...catch


🔹 Handling Errors in async/await

We can use try...catch to handle errors in an async function.

🔹 Example:

javascript

async function fetchData() { try { let response = await fetch('https://invalid-url.com'); let data = await response.json(); console.log(data); } catch (error) { console.error('Error fetching data:', error); } } fetchData();

If an error occurs, catch will handle it gracefully instead of crashing the program.


🔸 Comparison: async/await vs Promises

FeaturePromises (.then/.catch)async/await
SyntaxCallback-based chainingLooks like synchronous code
ReadabilityHarder (nested .then())Easier, cleaner
Error Handling.catch() neededtry...catch is simpler
PerformanceSimilarSimilar

🔹 Example with Promises (.then/.catch)

javascript

fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));

🔹 Same Example with async/await

javascript

async function fetchData() { try { let response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); let data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } } fetchData();

🎯 Both do the same thing, but async/await is cleaner and more readable!


🔹 When to Use async/await?

✅ When dealing with APIs, databases, or file reading
✅ When you need sequential execution of async tasks
✅ When you want to handle errors easily with try...catch


🔥 Final Thought

async/await makes JavaScript asynchronous code more readable, maintainable, and easier to debug. It's a powerful tool for working with Promises in a cleaner way.


Async/Await Concept in Javascript/LWC

  Concept of async and await in JavaScript async and await are used in asynchronous programming in JavaScript. They help us write clean...