Asynchronous JavaScript & Promises
JavaScript is single-threaded. To avoid freezing the user interface while fetching data or reading files, JavaScript handles long tasks asynchronously.
What is it?
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value.
Why is it used?
Eliminates deeply nested 'Callback Hell' and provides clean chaining via `.then()`, `.catch()`, and `.finally()`.
Detailed Explanation
Promise States:
1. Pending: Initial state; neither fulfilled nor rejected.
2. Fulfilled (Resolved): Operation completed successfully (`resolve(data)`).
3. Rejected: Operation failed (`reject(error)`).
Consuming Promises:
• `.then(result => ...)`: Executes on success.
• `.catch(error => ...)`: Catches any error along the chain.
• `.finally(() => ...)`: Executes regardless of success or failure (e.g. hiding loading spinners).
Syntax Structure
Syntax Blueprint
myPromise
.then(data => console.log(data))
.catch(err => console.error(err))
.finally(() => hideSpinner());
Code Example
JAVASCRIPT Code
// Simulated Database Fetch with Promise
function fetchCourseDetails(courseSlug) {
return new Promise((resolve, reject) => {
console.log("Fetching course details from server...");
setTimeout(() => {
if (courseSlug === "python") {
resolve({
title: "KLiC Advanced Python",
modules: 24,
price: 2500
});
} else {
reject(new Error("Course not found in database."));
}
}, 1000); // 1 second simulated network latency
});
}
// Consuming the Promise
fetchCourseDetails("python")
.then(course => {
console.log("Fetch Successful:", course.title, `(${course.modules} lessons)`);
})
.catch(err => {
console.error("Fetch Failed:", err.message);
})
.finally(() => {
console.log("Network request completed.");
});
Explanation of the Code
• Returns a Promise wrapping `setTimeout`.
• Simulates 1s delay before resolving with course data.
• Demonstrates `.then()` handling success and `.finally()` running cleanup.
Expected Output
Fetching course details from server...
(1 second pause)
Fetch Successful: KLiC Advanced Python (24 lessons)
Network request completed.
Real-World Application
All modern browser APIs (Fetch, Camera access, Geolocation, Notifications) return Promises.
Common Mistakes to Avoid
• Forgetting to return a promise in `.then()` handlers when chaining steps.
• Forgetting to attach a `.catch()` handler, triggering 'UnhandledPromiseRejection' warnings.
Quick Practice Challenge
Create a Promise that resolves with 'Success!' after 2 seconds using `setTimeout`.
Key Takeaways
• Promises represent future async values.
• Three states: Pending, Fulfilled, Rejected.
• Chain `.then()` for success and `.catch()` for errors.