start learning
Image 1
44740970977

Javascript Promises

In asynchronous programming, a PROMISE is an object that represents the eventual completion or failure of an asynchronous operation. It is a way to handle asynchronous operations in a more structured and manageable manner.

A promise can be in one of three states:

  1. Pending promise

    This is the initial state of a promise. It means that the asynchronous operation is still in progress and the final outcome is not yet determined.
  2. Fulfilled promise

    If the asynchronous operation is successful, the promise transitions to the fulfilled state. It means that the operation has completed successfully and any data produced by the operation is available.
  3. Rejected promise

    If the asynchronous operation encounters an error or fails for some reason, the promise transitions to the rejected state. It means that the operation did not complete successfully, and an error object containing the reason for failure is available.

Promises provide a way to handle the results of asynchronous operations using methods like .then() and .catch(). When a promise is fulfilled, the .then() method is called, allowing you to specify what should happen with the successful result. When a promise is rejected, the .catch() method is called, allowing you to handle any errors that occurred during the operation.

PROMISES help avoid callback hell and provide a more readable and structured way to work with asynchronous code. They allow you to chain multiple asynchronous operations together and handle success and failure cases in a more concise manner.
Here's examples that demonstrates the use of promises in JavaScript, along with HTML :


function fetchData() {
  return new Promise((resolve, reject) => {
    const data = 'This is the fetched data';
    if (data) {
      resolve(data); // Operation succeeded
    } else {
      reject(new Error('Failed to fetch data')); // Operation failed
    }
  });
}

fetchData()
  .then((data) => {
    console.log('Success:', data);
  })
  .catch((error) => {
    console.log('Error:', error.message);
  });
 

In this modified example, the fetchData() function returns a promise that represents the asynchronous operation to fetch data. Instead of using a timeout, we directly define and assign the data to the data variable.
If the data is available, we immediately resolve the promise with the data. Otherwise, we reject the promise with an error.

The rest of the code remains the same. We call the fetchData() function and chain the .then() and .catch() methods to handle the promise's fulfillment or rejection. If the operation succeeds, the .then() callback is executed, and we log the success message along with the fetched data to the console. If the operation fails, the .catch() callback is executed, and we log the error message to the console.
Same example using a timeout delay :


function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = 'This is the fetched data';
      if (data) {
      resolve(data); // Operation succeeded
      } else {
      reject(new Error('Failed to fetch data')); // Operation failed
      }
    }, 2000); // 2 seconds delay
  });
}

fetchData()
   .then((data) => {
    console.log('Success:', data);
  })
    .catch((error) => {
    console.log('Error:', error.message);
  });
 

In this example, we have a fetchData() function that returns a promise representing a simulated asynchronous operation to fetch data. Inside the promise's executor function, we use a timeout to simulate the delay.

When you run this JavaScript code, it will simulate an asynchronous operation that takes 2 seconds to complete. After the delay, the promise will either be fulfilled with the fetched data or rejected with an error, and the corresponding callback will be executed, logging the appropriate message to the console.
Another Example to display user Data :


<!DOCTYPE html>
<html>
<head>
  <title>Promise Example</title>
  <script>
    function getUserData() {
      return new Promise((resolve, reject) => {
        // Simulating an asynchronous operation with a timeout
        setTimeout(() => {
          const userData = { name: 'John Doe', age: 25, email: 'johndoe@example.com' };
          if (userData) {
            resolve(userData); // Operation succeeded
          } else {
            reject(new Error('Failed to fetch user data')); // Operation failed
          }
        }, 2000); // 2 seconds delay
      });
    }

    function displayUserData() {
      const resultContainer = document.getElementById('result');

             resultContainer.textContent = 'Loading...';

getUserData()
    .then((userData) => {
      resultContainer.textContent = `Name: ${userData.name}, Age: ${userData.age}, Email: ${userData.email}`;
    })
    .catch((error) => {
      resultContainer.textContent = 'Error: ' + error.message;
    });
}
  </script>
</head>
<body>
  <button onclick="displayUserData()">Display User Data</button>
  <p id="result"></p>
</body>
</html>
 

When you click the "Display User Data" button, it triggers the asynchronous operation, and after 2 seconds, the user data will be displayed in the paragraph element if the operation succeeds. Otherwise, an error message will be displayed if the operation fails.


Resources for Further Learning

Explore the possibilities and create unique effects on your web pages by using the interactive code editor

HTML

Write and customize HTML code

CSS

Add style and design to your web pages with CSS

JavaScript

Enhance interactivity with JavaScript code

Go to Code Editor