Skip to main content

Command Palette

Search for a command to run...

Async/Await in JavaScript: Writing Cleaner Asynchronous Code

Updated
3 min read
Async/Await in JavaScript: Writing Cleaner Asynchronous Code

Why async/await Was Introduced

Before async/await, we used:

  • callbacks (callback hell)

  • promises (.then chains)

Example with promises:

fetchData()
  .then(data => processData(data))
  .then(result => saveData(result))
  .catch(err => console.log(err));

Problem:

  • looks messy

  • hard to read

  • difficult to debug

So async/await was introduced to make async code look like normal synchronous code.

Async/Await = Syntactic Sugar

Important line (interview )

Async/await is syntactic sugar over promises.

Meaning:

  • it does not replace promises

  • it just makes them easier to write and read

How async Functions Work

When you write async before a function:

That function always returns a promise

Example

async function greet() {
  return "Hello";
}

greet().then(res => console.log(res));

Output:

Hello

Even though we returned a string, it becomes a resolved promise.

Await Keyword Concept

await is used to wait for a promise to resolve.
It pauses execution until the result is ready.

Example

function fetchData() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("Data received");
    }, 2000);
  });
}

async function getData() {
  let data = await fetchData();
  console.log(data);
}

getData();

Flow:

  1. fetchData() runs

  2. await waits

  3. data comes after 2 seconds

  4. then it prints

How It Improves Readability

Promise Style

fetchData()
  .then(data => {
    return processData(data);
  })
  .then(result => {
    console.log(result);
  });

Async/Await Style

async function run() {
  let data = await fetchData();
  let result = await processData(data);
  console.log(result);
}

Looks like normal step-by-step code

Error Handling with Async Code

We use try...catch with async/await.

Example

async function run() {
  try {
    let data = await fetchData();
    console.log(data);
  } catch (err) {
    console.log("Error:", err.message);
  }
}

Works just like normal error handling.

Comparison with Promises

Feature Promises (.then) Async/Await
Syntax Chain-based Clean & simple
Readability Harder Easier
Error handling .catch() try...catch
Flow Non-linear Looks linear

Real-Life Analogy

Think like this:

Promise

“Call me when work is done”

Async/Await

“Wait here until work is done, then continue”

Simple Real Example

function orderFood() {
  return new Promise(resolve => {
    setTimeout(() => resolve("Food delivered"), 2000);
  });
}

async function eat() {
  console.log("Ordering food...");
  let food = await orderFood();
  console.log(food);
}

eat();

Output:

Ordering food...
Food delivered

Final Summary

  • async makes a function return a promise

  • await waits for the promise to resolve

  • makes async code look synchronous

  • improves readability and debugging