JavaScript Promises

Promises in JavaScript allow us to handle asynchronous operations where the value is not known in advance when the promise is being created. A promise can have three states: pending, fulfilled, and rejected.

Promise States

A promise represents an asynchronous operation and can be in one of three states:

  • Pending: Initial state, neither fulfilled nor rejected
  • Fulfilled: The operation completed successfully
  • Rejected: The operation failed

Creating a Basic Promise

Here's how to create a simple promise:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Promises</title>
</head>
<body>
    <div id="output"></div>
    
    <script>
        // Creating a basic promise
        const myPromise = new Promise((resolve, reject) => {
            const success = true;
            
            setTimeout(() => {
                if (success) {
                    resolve("Promise fulfilled successfully!");
                } else {
                    reject("Promise was rejected!");
                }
            }, 1000);
        });
        
        // Using the promise
        myPromise
            .then(result => {
                document.getElementById("output").innerHTML = result;
                console.log(result);
            })
            .catch(error => {
                document.getElementById("output").innerHTML = error;
                console.log(error);
            });
    </script>
</body>
</html>

Real-World Example: Fetching Data

Here's a practical example using fetch API with promises:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fetch with Promises</title>
    <style>
        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
            padding: 20px;
        }
        .sample {
            font-size: 16px;
            font-weight: 500;
            color: #333;
            margin: 20px 0;
        }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
            border-radius: 4px;
        }
        button:hover {
            background: #0056b3;
        }
    </style>
</head>
<body>
    <h1>JavaScript Promises with Fetch API</h1>
    <div class="sample">Click the button to fetch user data</div>
    <button class="btn">Fetch Users</button>
    <div id="results"></div>
    
    <script>
        let sampleEle = document.querySelector(".sample");
        let resultsDiv = document.getElementById("results");
        
        document.querySelector(".btn").addEventListener("click", () => {
            sampleEle.innerHTML = "Loading...";
            resultsDiv.innerHTML = "";
            
            fetch("https://jsonplaceholder.typicode.com/users")
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(users => {
                    sampleEle.innerHTML = "Users loaded successfully:";
                    users.forEach(user => {
                        resultsDiv.innerHTML += `<p>${user.name} (@${user.username})</p>`;
                    });
                })
                .catch(error => {
                    sampleEle.innerHTML = "Error occurred: " + error.message;
                    console.error('Fetch error:', error);
                });
        });
    </script>
</body>
</html>

Promise Chaining

Promises can be chained to handle sequential asynchronous operations:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise Chaining</title>
</head>
<body>
    <div id="chain-output"></div>
    
    <script>
        function step1() {
            return new Promise(resolve => {
                setTimeout(() => resolve("Step 1 completed"), 1000);
            });
        }
        
        function step2(data) {
            return new Promise(resolve => {
                setTimeout(() => resolve(data + " ? Step 2 completed"), 1000);
            });
        }
        
        function step3(data) {
            return new Promise(resolve => {
                setTimeout(() => resolve(data + " ? Step 3 completed"), 1000);
            });
        }
        
        // Chain the promises
        step1()
            .then(result => {
                document.getElementById("chain-output").innerHTML = result;
                return step2(result);
            })
            .then(result => {
                document.getElementById("chain-output").innerHTML = result;
                return step3(result);
            })
            .then(result => {
                document.getElementById("chain-output").innerHTML = result;
            })
            .catch(error => {
                console.error("Error in chain:", error);
            });
    </script>
</body>
</html>

Promise Methods

JavaScript provides several utility methods for working with multiple promises:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise Methods</title>
</head>
<body>
    <div id="methods-output"></div>
    
    <script>
        const promise1 = Promise.resolve("First promise");
        const promise2 = Promise.resolve("Second promise");
        const promise3 = Promise.resolve("Third promise");
        
        // Promise.all - waits for all promises to resolve
        Promise.all([promise1, promise2, promise3])
            .then(results => {
                document.getElementById("methods-output").innerHTML = 
                    "<h3>Promise.all results:</h3>" + results.join("<br>");
            });
        
        // Promise.race - resolves with the first settled promise
        Promise.race([
            new Promise(resolve => setTimeout(() => resolve("Fast promise"), 100)),
            new Promise(resolve => setTimeout(() => resolve("Slow promise"), 500))
        ]).then(result => {
            setTimeout(() => {
                document.getElementById("methods-output").innerHTML += 
                    "<h3>Promise.race winner: " + result + "</h3>";
            }, 200);
        });
    </script>
</body>
</html>

Conclusion

Promises provide a cleaner way to handle asynchronous operations compared to callbacks, avoiding "callback hell." They support chaining for sequential operations and provide utility methods like Promise.all() and Promise.race() for handling multiple asynchronous tasks efficiently.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements