TGViewer
Web Development Web Development @web_dev_bds · 4.44K subscribers
Post #794 450
🌐 JavaScript Promises & Async/Await (Asynchronous Code) ⏳

Asynchronous programming allows your code to run tasks in the background (like fetching data from an API) without freezing the entire website.

👉 Understanding this is the key to mastering data fetching and complex frontend logic.

🔹 1. What is a Promise?

A Promise is a placeholder for a value that will be available in the future. Think of it like a buzzer at a restaurant: you don't have your food yet, but you have a "promise" that it's coming.

A Promise has 3 states:
• Pending: Still waiting for the result.
• Resolved (Fulfilled): Task finished successfully! ✅
• Rejected: Something went wrong. ❌

🔹 2. The Old Way: .then() and .catch()

Before 2017, we handled promises by "chaining" functions. While it works, it can get messy (known as "callback hell").

Example:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => print(data))
.catch(error => print("Error found!"));


🔹 3. The Modern Way: async and await

This is the industry standard. It makes asynchronous code look and behave like normal, top-to-bottom code.

• async: Put this before a function to tell JS it contains asynchronous code.
• await: Put this before a promise to tell JS "wait here until the data arrives."

Example:
async function getData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
print(data);
}


🔹 4. Handling Errors with try...catch

When using async/await, we use a try...catch block to handle errors gracefully (like a lost internet connection or a 404 error).

Example:
async function safeFetch() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
print(data);
} catch (error) {
print("Network error or invalid API!");
}
}


🔹 5. Why is this important?

• User Experience: Your site stays interactive while loading data.
• Performance: You can fetch multiple pieces of data at the same time.
• Clean Code: async/await is much easier to read and maintain than old-school callbacks.

🎯 What you should do

✔️ Understand the 3 states of a Promise
✔️ Master the async and await keywords
✔️ Learn to handle API errors using try...catch
  • ❤ 4
More from @web_dev_bds
  1. Oct 13, 2026Docker vs Kubernetes
  2. Oct 12, 2026Post #1054
  3. Oct 11, 2026CSS Tip Stop centring tooltips with 𝚝𝚛𝚊𝚗𝚜𝚕𝚊𝚝𝚎: -𝟻𝟶%. near the edge of the scree…
  4. Oct 9, 2026JavaScript CheatSheet
  5. Oct 8, 2026📕Pro tip if you're using Postgres: Set `application_name` in your app's DB connector/ORM/…
  6. Oct 7, 2026🚀 Beginner → Developer: What to Learn in 6 Months Want to become job-ready but don't know…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →