JavaScript Tutorial in Hindi #30 | Promises & Async Await(2025)
✅ 1. What is Asynchronous Programming?
- Code that runs in the background without blocking the main program.
- Useful for tasks like fetching data, reading files, timers.
- Lets the program keep running while waiting for operations to complete.
✅ 2. Introduction to Promises
- A Promise is an object representing a future result of an asynchronous operation.
- It can be in one of 3 states:
- Pending: Operation not finished yet.
- Fulfilled: Operation completed successfully.
- Rejected: Operation failed with an error.
✅ 3. Promise States
- Pending: Waiting for result.
- Fulfilled: Got result (success).
- 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");
});
.then()
handles success..catch()
handles errors..finally()
runs regardless of outcome.
✅ 5. Async/Await – Writing Cleaner Asynchronous Code
async
functions let you write async code like synchronous.- 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
- Forgetting to use
await
inside async functions. - Mixing
.then()
andasync/await
inconsistently. - Not handling errors with try/catch.
- Creating unnecessary Promises when async/await already handles it.