Skip to main content

Command Palette

Search for a command to run...

Asynchronous programming in JavaScript

Published
•3 min read•View as Markdown
Asynchronous programming in JavaScript
C

MERN stack developer passionate about technology and coding. Seeking opportunity to collaborate with developers working on challenging projects. I love to teach what I learn so I'm also a tech blogger. :-)

JavaScript is a single-threaded programming language which means only one thing can happen at a time. The JavaScript engine can only process one statement at a time in a single thread.

As we all know javascript is a synchronous programming language, but sometimes this default behaviour takes more time to execute the time-consuming operations such as network requests, file I/O, or database queries.

In synchronous programming, it executes only one thing at a time, when we are requesting some data from an API which might time a long time to process and might have to wait for the database connection and other operations, it blocks the main thread and it has to wait for the current code to execute completely then go to the next line of code.

That’s where asynchronous JavaScript comes into play. Asynchronous programming in JavaScript allows you to execute tasks concurrently, without blocking the execution of other code. This is particularly useful for handling time-consuming operations such as network requests, file I/O, or database queries.

JavaScript provides several mechanisms to handle asynchronous operations effectively. Here are the key concepts and approaches:

1. Callbacks

Callbacks are a traditional way to handle asynchronous operations in JavaScript. You provide a function as an argument to an asynchronous function, which will be invoked once the operation completes.

function Addtion(callback) {
  // An asynchronous operation
  setTimeout(() => {
    const data = 1;
    console.log(callback(data));
  }, 1000);
}

function add(data) {
 return data+3
}

Addtion(add);

2. Promises

Promises provide a more structured and readable way to handle asynchronous operations. A Promise represents the eventual completion (or failure) of an asynchronous operation and allows you to chain operations using then() and catch().

JavaScript Promises are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code. when callbacks inside the callbacks which eventually leads to callback hell and unmanageable code.

Syntax:

let promise = new Promise(function(resolve, reject){
     //do something
});

Example:

function fetchData() {
  return new Promise((resolve, reject) => {
    // An asynchronous operation
    setTimeout(() => {
      const data = 'Some data';
      if(data)
      resolve(data);
      else
      reject()
    }, 1000);
  });
}

fetchData()
  .then((data) => {
    console.log('Processing:', data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });

3. Async/await:

Async/await is a modern syntax that simplifies working with Promises. The async keyword is used to declare an asynchronous function and the await keyword is used to pause the execution of the function until a Promise is resolved or rejected.

async function getData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = 'Random data';
      if(data)
      resolve(data);
      else 
      reject()
    }, 1000);
  });
}

async function putData() {
  try {
    const data = await getData();
    console.log('Processing:', data);
  } catch (error) {
    console.error('Error:', error);
  }
}

putData();