Introducing Asynchronous Operations in JavaScript

Objective

After completing this lesson, you will be able to Use a few key techniques for writing asynchronous JavaScript.

Asynchronous Operations

Introduction

Asynchronous JavaScript allows JavaScript code to be executed in a non-blocking manner, meaning it does not have to wait for each operation to complete before moving on to the next one. This is particularly useful for tasks that take a significant amount of time or depend on external resources, such as fetching data from a server or reading from a file.

Let's look at a few key techniques for writing asynchronous JavaScript.

setTimeout

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
123456789
console.log("Start"); setTimeout(function() { console.log("Inside setTimeout"); }, 3000); console.log("End");

In this example, setTimeout is an asynchronous function. It waits 3000 milliseconds (3 seconds) before executing the function that logs "Inside setTimeout". But while setTimeout is waiting, the rest of the code continues to run, so "End" is logged before "Inside setTimeout".

Callbacks

A callback is a function passed into another function as an argument. The callback function can then be executed at a later time. This is one of the simplest ways to handle asynchronous operations.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
1234567891011
function fetchData(callback) { setTimeout(function() { console.log("Data fetched"); callback(); }, 2000); } fetchData(function() { console.log("Callback function executed"); });

In this example, the fetchData function takes a callback function as an argument and calls it after it logs "Data fetched".

Promise

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It returns a value that is either a resolved value or a reason why it rejected. Promises are more powerful and flexible than callbacks and form the basis of modern asynchronous JavaScript.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
12345678910
let promise = new Promise(function(resolve, reject) { setTimeout(function() { resolve('Data fetched!'); }, 2000); }); promise.then(function(data) { console.log(data); // 'Data fetched!' after 2 seconds });

Async/Await

This is a syntactic feature introduced in ES2017 that makes working with Promises much easier and more readable. It allows you to write asynchronous code that looks and behaves like synchronous code.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
12345678
async function fetchAndLogData() { let response = await fetch('https://api.example.com/data'); let data = await response.json(); console.log(data); } fetchAndLogData();

Note

Note that the fetch API returns a Promise, which is why we can use await with it. The await keyword can only be used inside an async function. It causes the async function to pause and wait for the Promise to resolve or reject, and then resumes the execution of the async function and returns the resolved value. If the Promise rejects, it throws an error, which can be caught using a try/catch block.

These techniques help make JavaScript more flexible and allow for more efficient execution of code, particularly in situations where you are dealing with operations that could take an unpredictable amount of time, such as network requests.

Add Interactivity to Your Blog Page

In this exercise, you'll use JavaScript to add interactivity to your blog page. You'll use an external JavaScript file similar to how you used an external CSS file.

Steps

  1. To start adding interactivity to your web page, you first have to create an external JavaScript file.

    1. Open a text editor or IDE and create a new file with a ".js" extension. Let's name it "script.js".

  2. In your HTML file, link to the external JavaScript file by adding a <script> element just before the closing </body> tag. The src attribute should contain the path to your JavaScript file.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    1234
    <body> <!-- Your existing HTML elements --> <script src="script.js"></script> </body>

  3. You want to display a thank you message when the user clicks the subscribe button.

    1. In "script.js", select the button using its id and add an event listener for the 'click' event.

    2. In the event handler function, display an alert with the thank you message.

      Refer to the following code snippet.

      Code Snippet
      Copy code
      Switch to dark mode
      123
      document.getElementById('subscribe-button').addEventListener('click', function() { alert('Thank you for subscribing!'); });

  4. When a blog title in the table is clicked, you want to display the blog title in an alert.

    1. Select the table rows using the table's id.

    2. Loop over the rows and, for each row, add an event listener for the 'click' event.

    3. In the event handler function, display an alert with the blog title (content of the first cell).

      Refer to the following code snippet.

      Code Snippet
      Copy code
      Switch to dark mode
      1234567
      var rows = document.getElementById('blog-posts').rows; for (var i = 0; i < rows.length; i++) { rows[i].addEventListener('click', function() { var blogTitle = this.cells[0].innerText; alert('You clicked on ' + blogTitle); }); }

  5. When a hyperlink in the list is clicked, you want to change its color to red.

    1. Select the hyperlinks using the list's id.

    2. Loop over the hyperlinks and, for each hyperlink, add an event listener for the 'click' event.

    3. In the event handler function, change the color of the hyperlink to red.

      Refer to the following code snippet.

      Code Snippet
      Copy code
      Switch to dark mode
      1234567
      var links = document.getElementById('favorite-blogs').getElementsByTagName('a'); for (var i = 0; i < links.length; i++) { links[i].addEventListener('click', function(event) { event.preventDefault(); // to prevent the page from navigating to the link this.style.color = 'red'; }); }

      Note

      Before running the JavaScript code, make sure to replace the dummy blog URLs with actual URLs. If you don't, clicking on the hyperlinks won't take you anywhere and the 'click' event listener will prevent the color change.

      This completes the JavaScript exercises. The behavior defined in the "script.js" file will now apply to the HTML document that links to it, making your blog page interactive.

Result

Observe the impact of adding JavaScript code to your web page.

The following web page shows the thank you message that displays after the user clicks the Subscribe button. It also shows that the color of the hyperlink changes to red when the item is selected.

The following web page shows an alert when a blog title in the table is selected. 

Log in to track your progress & complete quizzes