Lesson 11: Understanding Promises in JavaScript

Lesson Overview

In this lesson, we will learn about Promises in JavaScript, how they work, and how to use them to handle asynchronous operations.

Graphical Preview

Graphical Preview of Promises

Code Example


function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const data = { message: "Data fetched successfully!" };
            resolve(data);
        }, 2000);
    });
}

fetchData()
    .then(response => console.log(response.message))
    .catch(error => console.error("Error:", error));