Posted January 24Jan 24 You are reading Part 17 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 3]IntroductionJavaScript Promises provide a cleaner and more structured way to handle asynchronous operations compared to callbacks. Promises simplify async code and help avoid "callback hell" by allowing method chaining with .then(). This makes managing asynchronous sequences more readable and maintainable.Promises improve asynchronous programming in JavaScript by offering a structured way to handle success and failure cases. By chaining .then() calls and using .catch(), developers can write cleaner and more manageable async code. Understanding promises is crucial for working with modern JavaScript, especially with APIs and event-driven applications.1. What is a Promise?A Promise is an object representing the eventual completion (or failure) of an asynchronous operation. It has three possible states:Pending – The initial state, operation not yet completed.Fulfilled – The operation completed successfully.Rejected – The operation failed.Basic Syntax:let promise = new Promise((resolve, reject) => { // Async operation let success = true; if (success) { resolve("Operation was successful"); } else { reject("Operation failed"); } }); 2. Handling Promises with .then() and .catch()The .then() method is used to execute code when the promise is fulfilled, and .catch() handles errors when the promise is rejected.Example:let myPromise = new Promise((resolve, reject) => { setTimeout(() => { let success = true; success ? resolve("Data loaded successfully") : reject("Error loading data"); }, 2000); }); myPromise .then(response => { console.log(response); }) .catch(error => { console.error(error); }); Output:(Data loaded successfully) // If successful (Error loading data) // If rejected 3. Chaining Multiple .then() CallsOne of the major advantages of promises is the ability to chain multiple .then() methods, making the code more readable.Example:function fetchData() { return new Promise(resolve => { setTimeout(() => resolve("Step 1: Data Retrieved"), 1000); }); } function processData(data) { return new Promise(resolve => { setTimeout(() => resolve(data + " → Step 2: Data Processed"), 1000); }); } function displayData(data) { return new Promise(resolve => { setTimeout(() => resolve(data + " → Step 3: Data Displayed"), 1000); }); } fetchData() .then(result => processData(result)) .then(result => displayData(result)) .then(finalResult => console.log(finalResult)) .catch(error => console.error(error)); Output (after 3 seconds):Step 1: Data Retrieved → Step 2: Data Processed → Step 3: Data Displayed 4. Using Promises for API Calls (fetch Example)Promises are widely used for making network requests using the fetch API.Example:fetch('https://jsonplaceholder.typicode.com/posts/1') .then(response => response.json()) .then(data => console.log("Fetched Post:", data)) .catch(error => console.error("Fetch error:", error)); Output:Fetched Post: { "userId": 1, "id": 1, "title": "Sample Title", "body": "Sample Body" } 5. Advantages of Promises over CallbacksFeatureCallbacksPromisesReadabilityNested, harder to manageChaining, cleaner structureError HandlingError needs to be handled in each functionCentralized .catch()Multiple Async CallsDifficult to sequenceEasily chain with .then()You are reading Part 17 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 3]
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.