Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 24 - JavaScript Promises

A Promise in JavaScript represents a value that may be available now, in the future, or never. It is used to handle asynchronous operations like fetching data from a server. Asynchronous means out of time, which means, the value you expect does not have to be available at the exact time you need it. It may come at the time of request, or in few seconds the request, or never.


Example 1: Creating and Using a Promise

const myPromise = new Promise((resolve, reject) => {
    let success = true; // Change this to false to test rejection

    setTimeout(() => {
        if (success) {
            resolve("Data fetched successfully!");
        } else {
            reject("Error: Data fetch failed.");
        }
    }, 2000);
});

myPromise
    .then(result => console.log(result))  // Output if resolved: Data fetched successfully!
    .catch(error => console.log(error)); // Output if rejected: Error: Data fetch failed.
  • The Promise simulates an asynchronous task that resolves or rejects after 2 seconds.

Explanation

  • A Promise has three states:
    • pending ? Initial state, before completion or rejection.
    • fulfilled ? The operation was successful.
    • rejected ? The operation failed.
  • A Promise is created using new Promise() and takes a function with resolve and reject.
  • The .then() method handles fulfillment, while .catch() handles rejection.

Example 2: Fetching Data with Promises

function fetchUserData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            let data = { name: "Alice", age: 25 };
            resolve(data);
        }, 1500);
    });
}

fetchUserData()
    .then(user => console.log(`User: ${user.name}, Age: ${user.age}`))
    .catch(error => console.log(error));
  • Fetching user data using a Promise!

Try Your Hand

Steps:

  1. Create a File:

    • Name it lesson24-promises.html.
  2. Write the Code:

    • Copy the following code:

      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Lesson 24 - Promises</title>
      </head>
      <body>
      <script>
         function checkNumber(num) {
             return new Promise((resolve, reject) => {
                 setTimeout(() => {
                     if (num % 2 === 0) {
                         resolve(`${num} is even!`);
                     } else {
                         reject(`${num} is odd!`);
                     }
                 }, 1000);
             });
         }
      
         checkNumber(8)
             .then(message => console.log(message))  // Output: 8 is even!
             .catch(error => console.log(error));    // If odd: "Number is odd!"
      </script>
      </body>
      </html>
  3. Save the File.

  4. Preview in Browser and Check Console Output.


Experiment

  1. Modify fetchUserData() to reject the promise if data is missing.
  2. Create a function that returns a promise resolving after 3 seconds.

Key Takeaways

  • Promises handle asynchronous operations.
  • .then() runs when the promise resolves successfully.
  • .catch() handles promise rejection.