Unlocking the Power of Javascript Asynchronous Functions: A Comprehensive Guide

This article will help in unlocking the Power of Javascript Asynchronous Functions: A Comprehensive Guide for Javascript Developers.

Unlocking the Power of Javascript Asynchronous Functions: A Comprehensive Guide

Javascript is a single-threaded and non-blocking operation language that allows developers to write faster, high-performance code. Javascript is widely used for creating websites. Now Javascript is one of the most popular languages after Node.js. In this article, we will understand one of the core concepts of Javascript with diagrams and examples.

What are I/O operations and Non Blocking I/O?

Those operations that require some time to execute and depend on a third party (database, cloud storage, person’s input) are known as I/O Operations. In programming languages operations are executed one by one, because javascript is a non-blocking language it executes all the lines, and those operations that are time-consuming are asynchronous and executed in the background improving the overall performance and reducing the time-consumption.

But this can result in a real-time problem for instance, 

const user = users.get(1);

console.log(`${user.firstname} ${user.lastname}`)

In the above code, I was trying to get details from my file and show the details on my console, but I’m getting null, the reason behind its non-blocking operation, is that getting my user details from the database requires a unit of time which is completely undefined depending on the system performance. 

To deduce these issues Javascript brings 3 concepts which are:

  1. Asynchronous Programming
  2. Callback Functions
  3. Promises

What is Asynchronous Programming and How to Use Asynchronous Function in Javascript?

Asynchronous programming enables code to execute without blocking further execution.

As you can see in the above example the highlight potion is an asynchronous operation to resolve the non-blocking issues we will convert it into an asynchronous function

Now we have an asynchronous function that allows us to execute non-blocking operations. The asynchronous function will now return the content in my file, but how will we call it in our code and block our further execution until this operation is completed successfully?

Javascript Asynchronous Functions

const fs = require('fs').promises;
async function readFileAsync() {
        try {
                const data = await fs.readFile('example.txt', 'utf8');
                console.log("File content:", data);
        } catch (err) {
                console.error("Error reading file:", err);
        }
}


readFileAsync();

As you can see we have added await before fs.readFile, await will indicate that the executor is to halt until the result in fetch/return from the function then new line of code will be executed and now our file data is completely available in the data variable.

Callback Function and How to Use Callback Function in Javascript?

In the above example, my code depends upon the competition of the asynchronous function when the async function returns the value then my code will process to execute other operations, but for instance, I need to read two files and return their content, but waiting for first one then other will increase the time-consumption for my script to reduce this issue we have callback function allowing us to pass a function after all the parameters which will be executed after the call function return its value.

Callback Function

const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) {
    console.error("Error reading file:", err);
  } else {
    console.log("File content:", data);
  }
});


const fs = require('fs');


fs.readFile('example2.txt', 'utf8', (err, data) => {
  if (err) {
    console.error("Error reading file:", err);
  } else {
    console.log("File2 content:", data);
  }
});

In the above example, we have created two call-back functions which will be completely independent of the flow of the code as they will be triggered and then those functions will be running in the background without disturbing the flow of code.

Promise and How to Use Promises in Javascript?

In Javascript, promises are a very professional way of handling the asynchronous task and are also more efficient than callback functions.

To create a promise you need first to create a variable that holds a promise constructor which will take a function as a parameter, in that function, you will have two arguments which are resolve and reject. When your code has completed the task without any error you will call resolve and pass a parameter in it, however when your task has any error then you will call reject and pass the error or message.

Promises in Javascript

When calling a promise you need to specify two things, first is .then which will indicate the good case i.e. resolve potion and the argument sent through resolve can be accessed through parameter however .catch will indicate the reject potion of the code when your code will indicate reject your output will be in the catch block.


        const myPromise = new Promise((resolve, reject) => {
            // Simulate an asynchronous task
            setTimeout(() => {
                const success = true;
                if (success) {
                    resolve("Operation successful!"); // Fulfilled
                } else {
                    reject("Operation failed!"); // Rejected
                }
            }, 1000);
            
            });


        myPromise
            
            .then((result) => {
            console.log(result); // "Operation successful!"
            
            })
            
            .catch((error) => {
            console.error(error); // "Operation failed!"
            
            });
    

We have tried our best to give you an understanding of the javascript blocking I/O learn More About Javascript, Please visit our Node.js category to learn more about Node.js.

Leave a Comment