Asynchronous Programming In JavaScript & Browser APIs

Asynchronous Programming In JavaScript & Browser APIs

Introduction

In JavaScript understanding the asynchronous behavior of JavaScript is important for javascript developers.

Asynchronous programming allows developers to execute tasks concurrently and prevent the javascript "blocking" behavior.

At its core, asynchronous programming in JavaScript allows for executing tasks without waiting for each one to complete before moving on to the next.

JavaScript follows a synchronous model, where each operation is performed one after the other. However, asynchronous programming provides concurrent execution preventing the application from becoming unresponsive during time-intensive operations.

Ways to Achieve Asynchronous Code

Callback

Callback functions are a fundamental concept in asynchronous JavaScript. They involve passing functions as arguments to other functions, triggering their invocation once a specific task is complete. While effective, this approach can lead to callback hell, a situation where nested callbacks result in complex and hard-to-read code.

function fetchData(callback) {
  setTimeout(() => {
    const data = "Some data from the server";
    callback(data);
  }, 1000);
}
//The fetchdata function accepts a callback as a parameter

function processData(data, callback) {
  setTimeout(() => {
    const processedData = data.toUpperCase();
    callback(processedData);
  }, 1000);
}
//the function processdata accepts some data and callback as parameter

function displayResult(result) {
  console.log("Result:", result);
}
//the function displayresult simply just displays the data that is passed 

fetchData((data) => {
  processData(data, (processedData) => {
    displayResult(processedData);
  });
});
//this is an example of a callback where eachfunction takes another function 
//as a callback until it reaches the end of the execution.

Promises

A promise in JavaScript is just like a promise in real life. You promise something and it has two results either the promise has been completed or it has failed. In Java Script, a promise function gets two parameters which are resolve and reject.

A Promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected.

  • fulfilled: meaning that the operation was completed successfully.

  • rejected: meaning that the operation failed.

The actual syntax of creating a promise.

var promise = new Promise( function(resolve, reject) {
/* Promise content */
})

As it might be seen, a promise constructor takes one parameter which is a function that passes two variables called resolve and reject. That code is going to return two possible results. If the promise is fulfilled then the resolve method executes. If something goes wrong the promise is going to execute the reject method to allow us to handle the error.

Chaining Promises

When it comes to promises in JavaScript .then() and .catch() blocks are very handy methods to use. We can chain our promises with the .then() method and only use one .catch() method end of the chain to handle all exceptions that may occur during one of the then() tasks executions.

Async/Await

Async/Await is a new feature added to JavaScript in ES8 and it allows you to write asynchronous code synchronously.

All you have to do is write the word async before any regular function and it becomes a promise.

Adding await before a function makes the execution thread wait for the asynchronous task/promise to resolve before proceeding further.

When we add the await keyword, we introduce synchronous behavior to the application, i.e., promises will be executed synchronously. It is done by suspending further execution until the returned promise is fulfilled or rejected.

async function getData(){
  try{
    const result = await fetch("htttps://fetchsomedatafromtheserver.com/data")
    console.log(result)
  }catch(error){
    console.log(error)
  }
}
getData()

Let's walk you through the code.

The first step while using async/await is to make the javascript interpreter know that this piece of code or this function will run asynchronously. This is done by writing the keyword async in front of the function. In async/await the errors are handled using the try/catch block. The try/catch block runs the same way like .then and .catch. In try block all the important functionalities are written.

The next important keyword is the await keyword. Once Javascript hits this await keyword it will move out of that function, and do all the other tasks that are there in the program. As soon as the fetch has completed executing the request it will return the result in the result variable and later will console.log the result in the next line.

JavaScript Web APIs

JavaScript Web APIs are a collection of functions and protocols that enable JavaScript to interact with web browsers and give you access to certain parts and functionality of the browser.

Types of JavaScript Web APIs

Audio and Video APIs

The Audio and Video category of JavaScript Web APIs provides functionality for handling multimedia content. This includes APIs for playing audio and video files, capturing audio and video from devices, and manipulating media streams.

These APIs can be used to create interactive media players, video conferencing applications, audio recording tools, etc.

Background and Synchronization APIs

The Background and Synchronization category includes APIs that allow JavaScript applications to perform tasks in the background and synchronize data across different devices or browser instances.

These APIs enable developers to build features such as background data synchronization, push notifications, periodic background tasks, and offline data caching.

Device and Sensor APIs

This category of APIs provides access to various device-specific functionalities and sensor data. It includes APIs for accessing information about the user's device, such as battery status, network connectivity, geolocation, and orientation.

These APIs enable developers to create location-based services, augmented reality applications, device-specific optimizations, etc.

Document Object Model (DOM) Manipulation APIs

DOM Manipulation APIs allow JavaScript to interact with the HTML document structure, its elements, and its styles and attributes.

These APIs enable developers to dynamically modify the content and appearance of web pages, handle user interactions, and create responsive and interactive web applications.

File and Storage APIs

The File and Storage category provides APIs for working with files and data storage on the client side. It includes APIs for reading and writing files, accessing local file systems, managing client-side databases, and storing data using key-value pairs or structured storage.

These APIs are useful for building applications that require local data persistence, file management, or offline functionality.

Input and Events APIs

The Input and Events category covers user input and event-handling APIs. These APIs allow developers to capture and respond to user interactions, such as mouse clicks, keyboard inputs, touch gestures, and other events.

They also include APIs for handling input from various devices, such as game controllers or stylus pens.

Networking and Communication APIs

Networking and Communication APIs help facilitate communication between web applications and remote servers.

These APIs enable sending HTTP requests, fetching and manipulating data from remote sources, establishing WebSocket connections for real-time communication, and implementing server-side communication protocols such as WebRTC.

They are fundamental for building web applications that interact with backend services or provide real-time collaboration features.

Security and Privacy APIs

Security and Privacy APIs offer mechanisms to protect user data and enhance web application security.

They include APIs for handling user authentication and authorization, securing network communications using encryption and certificates, managing browser permissions, and preventing common security vulnerabilities like cross-site scripting (XSS) or cross-site request forgery (CSRF).