Mastering Asynchronous JavaScript

Sanjana Human In Tech
2 min readAug 9, 2024

--

Asynchronous programming in JavaScript allows you to perform tasks without blocking the main thread, enabling your code to handle multiple operations simultaneously.

This is essential for maintaining a responsive user interface, particularly in development, where tasks like fetching data from a server, reading files, or waiting for user input can take time.

Key Concepts in Asynchronous JavaScript:

Callbacks: The original way for handling asynchronous operations.

  • A function passed as an argument to another function, which gets executed after an operation completes.
  • Drawback here is — It can lead to “callback hell,” where nested callbacks become hard to manage and read.
function fetchData(callback) {
setTimeout(() => {
callback('Data received');
}, 1000);
}

fetchData((data) => {
console.log(data);
});

Promises : To avoid “callback hell” Promises are introduced to simplify the process of asynchrnous events.

  • A Promise represents a value that may be available now, or in the future, or never.
  • States: Pending, Fulfilled, Rejected.
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data received');
}, 2000);
});
};

fetchData().then(data => console.log(data));

Async-Await: To make it more readable and easy to manage, JavaScript introduced the way to write the code in synchronous manner.

Here, async functions return a Promise, and await pauses the execution of the function until the Promise resolves.

const fetchData = async () => {
const data = await new Promise((resolve) => {
setTimeout(() => {
resolve('Data received');
}, 2000);
});
console.log(data);
};

fetchData();

SetTimeOut and SetInterval :

  • setTimeout: Executes a function once after a specified delay.
  • setInterval: Repeatedly executes a function at specified intervals.
setTimeout(() => {
console.log('Executed after 2 seconds');
}, 2000);

setInterval(() => {
console.log('Executed every 2 seconds');
}, 2000);

Use Cases:

  • Fetching data from APIs
  • Handling user inputs and events
  • Animations and timers
  • File I/O operations

Why Asynchronous Programming is Important:

  • Non-blocking operations: Prevents the UI from freezing while waiting for a task to complete.
  • Improved performance: Allows the execution of multiple tasks concurrently, leading to faster and more efficient applications.
  • User experience: Enhances the user experience by making applications more responsive and interactive.

--

--

Sanjana Human In Tech
Sanjana Human In Tech

Written by Sanjana Human In Tech

A React Native front-end enthusiast and dedicated development engineer, eager to expand knowledge on development techniques and collaborate with others.

No responses yet