30 Days of JavaScript: Asynchronous JavaScript and Promises — Day 5

30 Days of JavaScript: Building a Portfolio Website — Day 30
30 Days of JavaScript: Asynchronous JavaScript and Promises — Day 5

Learn asynchronous JavaScript in Day 5 of our tutorial series. Understand callbacks, Promises, async/await, and the Fetch API for seamless web application performance.

Greetings, JavaScript enthusiasts! Welcome back to Day 5 of our 30-day JavaScript tutorial series, where we continue our deep dive into the intricacies of this versatile language. Today, we venture into the fascinating world of asynchronous programming—a fundamental aspect of modern JavaScript that enables you to build responsive and high-performing web applications. Here’s what we’ll be covering today:

Table of Contents

By the end of today’s lesson, you will have a solid understanding of asynchronous JavaScript, empowering you to build seamless, responsive applications that engage users. Let’s dive in and continue our exciting JavaScript journey!

Understanding Asynchronous Programming

Asynchronous programming helps manage time-consuming tasks, such as fetching data from an API or processing large datasets, without blocking the main thread. This paradigm allows for the execution of non-blocking code, keeping your application responsive even when handling resource-intensive tasks.

Callbacks, Promises, and Async/Await

Callbacks are the earliest approach to handling asynchronous tasks in JavaScript. A callback is a function passed as an argument to another function, which is then executed at a later time. Let’s examine a simple example, starting with a beginner-level callback:

/**
 * Function that prints a greeting message after a delay.
 * @param {Function} callback - The callback function to execute after the delay.
 */
function printGreeting(callback) {
  setTimeout(() => {
    const greeting = 'Hello, world!';
    callback(greeting);
  }, 1000);
}

/**
 * Logs the greeting to the console.
 * @param {string} greeting - The greeting message.
 */
printGreeting((greeting) => {
  console.log(greeting);
});

For a more intermediate example, let’s fetch data using callbacks:

/**
 * Fetch data from the provided URL and handle the response using a callback.
 * @param {string} url - The URL to fetch data from.
 * @param {Function} callback - The callback function to handle the response or error.
 */
function fetchData(url, callback) {
  const xhr = new XMLHttpRequest();
  xhr.onreadystatechange = () => {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        callback(null, JSON.parse(xhr.responseText));
      } else {
        callback(new Error(`Request failed with status ${xhr.status}`));
      }
    }
  };
  xhr.open('GET', url);
  xhr.send();
}

/**
 * Callback function to handle the response or error.
 * @param {Error|null} error - The error object, if any.
 * @param {Object|null} data - The fetched data.
 */
fetchData('https://jsonplaceholder.typicode.com/todos/1', (error, data) => {
  if (error) {
    console.error('Error:', error);
  } else {
    console.log('Data:', data);
  }
});

Callbacks can lead to “callback hell” when dealing with multiple nested callbacks, resulting in hard-to-read and maintain code.

Fetch API and Making HTTP Requests

The Fetch API is a modern and powerful way to make HTTP requests in JavaScript. It is built on Promises, making it easy to use with async/await.

Here’s a beginner-level example of using the Fetch API:

/**
 * Fetch data from the provided URL using the Fetch API.
 * @param {string} url - The URL to fetch data from.
 */
fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then((response) => response.json())
  .then((data) => {
    console.log('Data:', data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });

For a more advanced example, let’s create a function that fetches data from an API, handles pagination, and combines the results:

/**
 * Fetch all paginated data from the provided URL.
 * @param {string} url - The base URL to fetch data from.
 * @param {number} [limit=10] - The number of items per page.
 * @returns {Promise<Array>} A promise that resolves to an array of all fetched data.
 */
async function fetchAllData(url, limit = 10) {
  let currentPage = 1;
  let hasMoreData = true;
  const allData = [];

  while (hasMoreData) {
    const response = await fetch(`${url}?_page=${currentPage}&_limit=${limit}`);
    const data = await response.json();

    allData.push(...data);
    currentPage++;

    if (data.length < limit) {
      hasMoreData = false;
    }
  }

  return allData;
}

/**
 * Fetches and logs all items from the paginated API.
 */
fetchAllData('https://jsonplaceholder.typicode.com/todos')
  .then((data) => {
    console.log(`Fetched ${data.length} items`);
  })
  .catch((error) => {
    console.error('Error:', error);
  });
Conclusion

In conclusion, we’ve explored the core concepts of asynchronous programming in JavaScript, including callbacks, Promises, and async/await. By mastering these techniques, you can build more responsive web applications that handle complex tasks without freezing the user interface.

We’ve also covered the Fetch API, which simplifies making HTTP requests, allowing you to retrieve data from external sources efficiently. These tools are vital for creating modern web applications that interact with APIs and manage asynchronous tasks seamlessly.

As we move forward, we’ll dive into some of the powerful modern JavaScript features, including arrow functions, template literals, destructuring, and modules. These features will enhance the readability and maintainability of your code, making you a more efficient developer.

What’s Next?

In Day 6, we’ll explore modern JavaScript features like arrow functions, template literals, and destructuring. These concepts will help you write cleaner, more efficient code and prepare you for working with more advanced patterns in JavaScript development. Stay tuned for another exciting chapter in your JavaScript journey!

Next: 30 Days of JavaScript: Modern JavaScript (ES6+) — Day 6

Leave a Comment

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top