Synchronous and Asynchronous — Understanding JavaScript API Requests and Responses in the Data Fetching lifecycle

rodcast

Rodrigo Castilho

Posted on April 24, 2023

Synchronous and Asynchronous — Understanding JavaScript API Requests and Responses in the Data Fetching lifecycle

Synchronous and Asynchronous

Before this article, I mentioned to you that I would start the articles series and I created an Introduction, V8 JavaScript engine, Callbacks, and about the AJAX and XMLHttpRequest. If you lost what I did, check it:

In this article series, I’ll not explain the concept of Fetch API or Promises but don’t worry that I’ll explain it in the next article.

Never Forget: JavaScript is a single-threaded and interpreted language, not a compiled one.

The browser reads a script containing JavaScript code from top-to-bottom in sequential order and blocks long-running tasks such as network requests and I/O events.

Basically, synchronous code is executed sequentially, one line of code at a time, and the next line of code cannot be executed until the previous one has finished executing. On the other hand, asynchronous code allows for multiple lines of code to be executed simultaneously, without having to wait for the previous line to finish executing.

What are the differences between synchronous and asynchronous?

Synchronous code execution is straightforward to reason about, as it follows a linear execution pattern. However, it can lead to performance issues when dealing with long-running tasks, as it can cause the browser to freeze and become unresponsive. In contrast, asynchronous code execution can be more complex, as it requires handling callbacks, promises, or async/await functions. However, it allows for non-blocking operations, which means that the browser can continue to run other code while waiting for a response from an asynchronous operation.

What are the types of synchronous in JavaScript?

Synchronous functions: A synchronous function will execute its code sequentially, blocking the execution of other code until it has been completed. These types of functions are commonly used for operations that can be completed quickly, such as simple calculations or data manipulations. See the example below using this feature:

    function add(x, y) {
      return x + y;
    }

    console.log(add(10, 2)); // Output: 12
Enter fullscreen mode Exit fullscreen mode

Synchronous loops: Loops in JavaScript are typically synchronous, which means that the loop will block the execution of other code until it has been completed. However, some loop constructs, such as the for…of loop, can be used with asynchronous operations using the await keyword. See the example below using this feature:

    const vowels = ["a", "e", "i", "o", "u"];

    for (const vowel of vowels) {
      console.log(vowel);
    }

    /**
      Output:
      a
      e
      i
      o
      u
    */
Enter fullscreen mode Exit fullscreen mode

Synchronous operations with the DOM: Some operations that involve manipulating the DOM (Document Object Model) are synchronous, such as setting the text content of an element or getting the size of an element. See the example below using this feature:

    const element = document.getElementById("element-id");
    element.textContent = "Hello world!";
Enter fullscreen mode Exit fullscreen mode

What are the types of asynchronous in JavaScript?

setTimeout(): This method is used to delay the execution of a function for a specified amount of time (in milliseconds). It is often used to simulate a delay or to schedule a function to run in the future. See the example below using this feature:

    setTimeout(() => {
      console.log("Delayed function after 1 second (1000 milliseconds)");
    }, 1000);
Enter fullscreen mode Exit fullscreen mode

setInterval(): This method is used to repeatedly execute a function at a specified interval (in milliseconds). It is often used to create animations or to periodically update data on a webpage. See the example below using this feature:

    setInterval(() => {
      console.log("Repeated function after 1 second (1000 milliseconds)");
    }, 1000);
Enter fullscreen mode Exit fullscreen mode

Event listeners: Event listeners are used to listening for and responding to events that occur on a web page, such as a button click or a page load. They allow for asynchronous handling of user interactions and can be used to create interactive and dynamic web applications. See the example below using this feature:

    const element = document.getElementById("element-id");
    element.addEventListener("click", () => {
      console.log("element-id clicked");
    });
Enter fullscreen mode Exit fullscreen mode

Promises: Promises are a way to handle asynchronous operations in a more readable and manageable way. They allow you to define a chain of actions that should be executed when an asynchronous operation succeeds or fails. See the example below using this feature:

    const delay = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("Promise resolved");
      }, 1000);
    });

    delay
      .then((result) => {
        console.log(result); // Output: Promise resolved
      })
      .catch((error) => {
        console.error(error); // Output: error value
      });
Enter fullscreen mode Exit fullscreen mode

Where happens synchronous and asynchronous in the V8 engine?

Synchronous and asynchronous operations are executed in different parts of the engine.

Synchronous operations in JavaScript are executed on the main thread of the V8 engine, which is responsible for executing JavaScript code in a single-threaded. When a synchronous operation is executed, the V8 engine blocks the main thread until the operation is completed. This can lead to performance issues if the operation takes a long time to complete, as it will block other JavaScript code from running on the main thread.

Asynchronous operations in JavaScript are executed on a separate thread, outside of the main thread of the V8 engine. When an asynchronous operation is initiated, such as making an HTTP request or reading a file from Drive, the main thread continues to execute other JavaScript code while the asynchronous operation runs in the background. Once the operation is completed, a callback function is executed on the main thread to handle the result of the operation.

Which one should I use?

The choice between synchronous and asynchronous programming ultimately depends on the specific requirements and constraints of the task at hand. However, the choice between synchronous and asynchronous programming ultimately depends on the specific requirements and constraints of the task at hand, and both approaches have their strengths and weaknesses.

In some cases, a combination of both synchronous and asynchronous programming may be necessary to achieve the desired outcome. In general, however, asynchronous requests should be preferred to synchronous requests for performance reasons.

So, If you want to know more about promises, and async/await, please wait for the next article that I’ll publish.

Thank you for reading, I hope this article can somehow have increased your knowledge base about it.

💖 💪 🙅 🚩
rodcast
Rodrigo Castilho

Posted on April 24, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related