Javascript Asynchronous Programming

1/1/1970

Javascript Asynchronous Programming

What is Asynchronous Programming?

Why is it Important?

1. Synchronous Code (Blocking)

console.log("Start");
for (let i = 0; i < 1e9; i++) {}  // Simulating a slow operation
console.log("End");
 
// If the loop takes **5 seconds**, the whole program is stuck for **5 seconds**.

2. Asynchronous Code (Non-Blocking)

console.log("Start");
 
setTimeout(() => {
  console.log("Inside setTimeout");
}, 2000);  // Executes after 2 seconds
 
console.log("End");
//  The `setTimeout()` function runs after the main execution finishes.
Start
End
Inside setTimeout (after 2 seconds)

Ways to Handle Asynchronous Code

1. Callbacks (Old Method) : A function is passed as an argument and runs after a task completes.

function fetchData(callback) {
  setTimeout(() => {
    callback("Data received!");
  }, 2000);
}
// `Callback()` is passed as argument in `setTimeout()` and will run after `setTimeout()` complete, i.e. after 2000 ms
fetchData((message) => {
  console.log(message);
});

2. Promises (.then .catch) : A better way to handle async tasks.

fetch("https://jsonplaceholder.typicode.com/posts")
  .then(response => response.json())
  .then(data => console.log("Data:", data))
  .catch(error => console.error("Error:", error));

3. Async/Await (Best Method) : Modern and more readable way to write async code.

async function fetchData() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts");
    const data = await response.json();
    console.log("Data:", data);
  } catch (error) {
    console.error("Error:", error);
  }
}
 
fetchData();
Method Description Pros Cons
Callbacks Function inside another function Simple for small tasks Leads to "Callback Hell"
Promises (.then .catch) Handles async tasks with .then() Avoids nested callbacks Can still get messy with many .then()
Async/Await (try...catch) Modern way, looks like sync code More readable, easy error handling Works only with Promises

Difference Between Async/Await and Promises

1. Promises with .then() and .catch() (ES6+)

export const create = (req, res) => {
  const userData = new User(req.body);
 
  if (!userData) {
    return res.status(404).json({ msg: "User data not found" });
  }
 
  userData.save()
    .then(saveData => {
      res.status(200).json(saveData);
    })
    .catch(error => {
      res.status(500).json({ error: error });
    });
}

2. Async/Await (ES2017)

export const create = async (req, res) => {
  try {
    const userData = new User(req.body);
 
    if (!userData) {
      return res.status(404).json({ msg: "User data not found" });
    }
 
    const saveData = await userData.save();
    res.status(200).json(saveData);
 
  } catch (error) {
    res.status(500).json({ error: error });
  }
}

When to Use Which?