JavaScript Tutorial in Hindi #30 | Promises & Async Await(2025)

✅ 1. What is Asynchronous Programming?

  1. Code that runs in the background without blocking the main program.
  2. Useful for tasks like fetching data, reading files, timers.
  3. Lets the program keep running while waiting for operations to complete.

✅ 2. Introduction to Promises

  1. A Promise is an object representing a future result of an asynchronous operation.
  2. It can be in one of 3 states:
  3. Pending: Operation not finished yet.
  4. Fulfilled: Operation completed successfully.
  5. Rejected: Operation failed with an error.

✅ 3. Promise States

  1. Pending: Waiting for result.
  2. Fulfilled: Got result (success).
  3. Rejected: Got error (failure).

Example:

js
CopyEdit
const myPromise = new Promise((resolve, reject) => {
// Async operation here
const success = true;

if (success) {
resolve("Done!");
} else {
reject("Error occurred");
}
});

✅ 4. Chaining Promises: then, catch, finally

js
CopyEdit
myPromise
.then(result => {
console.log("Success:", result);
})
.catch(error => {
console.error("Failed:", error);
})
.finally(() => {
console.log("Promise completed");
});
  1. .then() handles success.
  2. .catch() handles errors.
  3. .finally() runs regardless of outcome.

✅ 5. Async/Await – Writing Cleaner Asynchronous Code

  1. async functions let you write async code like synchronous.
  2. Use await to wait for a Promise to resolve or reject.

Example:

js
CopyEdit
async function fetchData() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching data:", error);
}
}

fetchData();

✅ 6. Practical Examples

Promise Example

js
CopyEdit
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

wait(2000).then(() => console.log("Waited 2 seconds"));

Async/Await Example

js
CopyEdit
async function countDown() {
for (let i = 3; i > 0; i--) {
console.log(i);
await wait(1000);
}
console.log("Go!");
}

countDown();

✅ 7. Common Mistakes

  1. Forgetting to use await inside async functions.
  2. Mixing .then() and async/await inconsistently.
  3. Not handling errors with try/catch.
  4. Creating unnecessary Promises when async/await already handles it.