Learn Asynchronous Javascript with examples

Asynchronous JavaScript


Asynchronous JavaScript is a programming approach that enables some script components to operate in the background as other script components are being executed. When performing I/O tasks that necessitate waiting for a response, such as obtaining data from a server or accessing the file system, this technique is extremely helpful. We will discuss asynchronous JavaScript in this article and offer code examples.

What is Asynchronous JavaScript?

JavaScript can only run one piece of code at a time because it is a single-threaded programming language. As a result, the browser will stall while working with time-consuming tasks, such as network queries, until the operation is finished. This issue can be resolved by using asynchronous JavaScript, which enables the script to carry on while the time-consuming task is carried out in the background.

Callbacks, promises, and async/await functions are the most popular methods for implementing asynchronous JavaScript.

Callbacks

A callback is a function that is passed as an argument to another function and is executed once that function has completed. Callbacks are a common way of handling asynchronous operations in JavaScript. Here's an example:

function fetchData(url, callback) {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.onload = () => {
    if (xhr.readyState === 4 && xhr.status === 200) {
      callback(xhr.responseText);
    }
  }
  xhr.send();
}

fetchData('https://jsonplaceholder.typicode.com/posts/1', (response) => {
  console.log(response);
});


In this example, the fetchData function takes a URL and a callback function as arguments. The function creates a new XMLHttpRequest object, sets the HTTP method to GET, and sends the request. Once the request is complete, the onload event is triggered, and the response data is passed to the callback function.

Promises

Promises provide a cleaner way of handling asynchronous operations than callbacks. A promise represents a value that may not be available yet, but will be at some point in the future. Promises have three states: pending, fulfilled, and rejected. Once a promise is fulfilled or rejected, it cannot change its state. Here's an example:

function fetchData(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onload = () => {
      if (xhr.readyState === 4 && xhr.status === 200) {
        resolve(xhr.responseText);
      } else {
        reject(xhr.statusText);
      }
    }
    xhr.onerror = () => {
      reject(xhr.statusText);
    }
    xhr.send();
  });
}

fetchData('https://jsonplaceholder.typicode.com/posts/1')
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.error(error);
  });

In this example, the fetchData function returns a new Promise object. The function creates a new XMLHttpRequest object, sets the HTTP method to GET, and sends the request. Once the request is complete, the onload event is triggered. If the response is successful, the promise is fulfilled, and the response data is passed to the then method. If the response is unsuccessful, the promise is rejected, and the error is passed to the catch method.

Async/await

Async/await is a more recent addition to JavaScript and provides a cleaner way of writing asynchronous code. The async keyword is used to define a function that returns a promise, while the await keyword is used to pause the execution of the function until the promise is fulfilled or rejected. Here's an example:

function fetchData(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onload = () => {
      if (xhr.readyState === 4 && xhr.status === 200) {
        resolve(xhr.responseText);
      } else {
        reject(xhr.statusText);
      }
    }
    xhr.onerror = () => {
      reject(xhr.statusText);
    }
    xhr.send();
  });
}

async function getData() {
  try {
    const response = await fetchData('https://jsonplaceholder.typicode.com/posts/1');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

getData();


The fetchData function in this example produces a promise that either resolves with the returned data or rejects with an error. The async nature of the getData function allows it to utilize the await keyword to suspend execution until the promise delivered by fetchData is fulfilled or denied.

When you use the getData function, it waits for the promise to be resolved or denied before proceeding. If the promise is kept, the response data is recorded in the console. If the promise is refused, an error message is sent to the console.


Since async and await allow you to create asynchronous code that appears like synchronous code, they can make your code easier to understand and write. It is crucial to remember, however, that async and await are built on top of promises, and they are not a replacement for promises. In fact, async functions always return promises, and you should still use the then and catch methods to handle promise resolution and rejection if you need to.


Finally, asynchronous JavaScript is a valuable feature that allows us to construct non-blocking code that may accomplish work in the background while the main thread is still running. We can construct fast and responsive web apps that can manage a high number of requests without interrupting the user interface by using callbacks, promises, and async/await. Knowing how to deal with asynchronous code is a necessary ability for any web developer, and it may assist you in creating quicker and more responsive online apps.

I hope you like this post; please leave a comment and share it with your friends, and please check out our other similar blogs.



Post a Comment

Previous Post Next Post