Sitemap
Prince Kumar Chaurasia

Prince Kumar Chaurasia

Javascript Beyond Basics

1 min readApr 18, 2025

--

Learning the depth of JavaScript

Callbacks sometimes get messy : The Callback hell

getData(function(data) {
getMoreData(data, function(moreData) {
getEvenMoreData(moreData, function(finalData) {
// 😵 Welcome to Callback Hell
});
});
});

So, JS introduced Promises.

A Promise is an object representing the eventual result (or failure) of an async operation.

const promise = new Promise((resolve, reject) => {
// async operation
let success = true;

if (success) {
resolve("Done!");
} else {
reject("Failed!");
}
});

You can use .then() and .catch() to handle the result.

promise
.then((result) => console.log(result))
.catch((error) => console.log(error));

Promise States

  1. Pending — not resolved or rejected yet
  2. Fulfilled — resolve() called
  3. Rejected — reject() called

Once fulfilled or rejected, it’s settled.

Get Prince Kumar Chaurasia’s stories in your inbox

Join Medium for free to get updates from this writer.

Instead of chaining .then() calls, we can use async and await in a function.

async function getUser() {
try {
const data = await fetchUser();
console.log(data);
} catch (err) {
console.log("Error:", err);
}
}

Behind the scenes:

  • await pauses the function until the promise resolves
  • It resumes only when the data is available
  • It’s syntactic sugar over promises but way cleaner

You can also use multiple awaits.

async function loadData() {
const user = await fetchUser();
const posts = await fetchPosts(user);
console.log(posts);
}

Each await happens sequentially. You can also run them in parallel with:

const [user, posts] = await Promise.all([fetchUser(), fetchPosts()]);

Things to remember while using async & await

  • You must use await inside an async function.
  • Always wrap with try/catch for error handling.
  • await blocks only within the function, not the whole program.

--

--