JavaScript Promises

A JavaScript Promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises simplify the management of asynchronous tasks by providing then, catch, and finally methods for handling outcomes.

Key Topics

Promise Basics

A Promise is created using the Promise constructor, which takes a callback function with two arguments: resolve (for successful outcomes) and reject (for failures).

const myPromise = new Promise((resolve, reject) => {
    const success = true;
    if (success) {
        resolve("Operation successful!");
    } else {
        reject("Operation failed!");
    }
});
myPromise
    .then((message) => {
        console.log(message);
    })
    .catch((error) => {
        console.error(error);
    });

Output

> Operation successful!

Explanation: The resolve callback is invoked for success, and the result is handled in the then block. The catch block is used for errors.

Handling Promises

Promises can handle both success and failure scenarios using the then and catch methods.

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("Data fetched successfully!");
        }, 2000);
    });
}
fetchData()
    .then((data) => {
        console.log(data);
    })
    .catch((error) => {
        console.error(error);
    });

Output

> Data fetched successfully!

Explanation: The fetchData function returns a Promise that resolves with a success message after a delay, which is then logged in the then block.

Chaining Promises

Multiple promises can be chained together to perform sequential asynchronous tasks.

function step1() {
    return new Promise((resolve) => {
        setTimeout(() => resolve("Step 1 complete"), 1000);
    });
}
function step2() {
    return new Promise((resolve) => {
        setTimeout(() => resolve("Step 2 complete"), 1000);
    });
}
step1()
    .then((result1) => {
        console.log(result1);
        return step2();
    })
    .then((result2) => {
        console.log(result2);
    });

Output

> Step 1 complete

> Step 2 complete

Explanation: The result of step1 is used to initiate step2, demonstrating sequential execution of asynchronous tasks.

JavaScript Usage in DOM

Below is a complete DOM example where a Promise is used to fetch and display data dynamically.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Promises in DOM</title>
</head>
<body>
    <button onclick="loadData()">Load Data</button>
    <p id="output"></p>

    <script>
        function fetchData() {
            return new Promise((resolve) => {
                setTimeout(() => resolve("Data loaded successfully!"), 1500);
            });
        }
        function loadData() {
            fetchData()
                .then((data) => {
                    document.getElementById("output").textContent = data;
                });
        }
    </script>
</body>
</html>

Key Takeaways

  • Promises: Simplify handling of asynchronous tasks by resolving or rejecting outcomes.
  • Chaining: Allows sequential execution of multiple asynchronous operations.
  • Error Handling: Use catch to gracefully manage errors in promises.
  • DOM Integration: Use promises to dynamically update UI content after asynchronous tasks.