Give an example of asynchronous promises on real time

Give an example of asynchronous promises on real time

This example employs the Fetch API, a popular tool for initiating HTTP requests in JavaScript.

// Function to simulate fetching data from an API
function fetchData() {
  // Simulating an API endpoint
  const apiUrl = 'https://jsonplaceholder.typicode.com/todos/1';

  // Returning a promise that represents the asynchronous operation
  return new Promise((resolve, reject) => {
    // Using the Fetch API to make an HTTP GET request
    fetch(apiUrl)
      .then(response => {
        // Checking if the request was successful (status code 200)
        if (response.ok) {
          // Parsing the JSON response and resolving the promise with the data
          return response.json();
        } else {
          // If the request was not successful, rejecting the promise with an error
          reject(new Error(`Failed to fetch data. Status: ${response.status}`));
        }
      })
      .then(data => {
        // Resolving the promise with the fetched data
        resolve(data);
      })
      .catch(error => {
        // Handling any errors that may occur during the fetch operation
        reject(error);
      });
  });
}

// Using the fetchData function with promises
fetchData()
  .then(data => {
    // Successfully fetched data, so we can work with it here
    console.log('Fetched data:', data);
  })
  .catch(error => {
    // An error occurred during the fetch operation, handle it here
    console.error('Error:', error.message);
  });

In this example,

  1. ThefetchData function returns a promise that represents the asynchronous operation of fetching data from an API.

  2. Thefetch function is used to make an HTTP GET request to a specific API endpoint (https://jsonplaceholder.typicode.com/todos/1 in this case).

  3. The promise is resolved with the parsed JSON data if the request is successful.

  4. If there is an error during the fetch operation (e.g., network issues or a non-successful HTTP status code), the promise is rejected with an appropriate error message.

  5. The then and catch methods are used to handle the success and error cases, respectively, when using the fetchData function.

In conclusion, asynchronous promises play a vital role in managing asynchronous operations in JavaScript. They offer a method for handling the eventual success or failure of an operation, allowing for more structured and maintainable code. The Fetch API, as demonstrated in the example, exemplifies this by returning a promise for HTTP requests, which can be resolved or rejected depending on the request's outcome. This approach makes tasks like fetching data from APIs more manageable and less prone to errors.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!