Javascript Beyond Basics
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
- Pending — not resolved or rejected yet
- Fulfilled —
resolve()called - 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:
awaitpauses 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
awaitinside anasyncfunction. - Always wrap with
try/catchfor error handling. awaitblocks only within the function, not the whole program.


![Infinite Scroll using React & JavaScript — [Asked in Machine Coding Rounds of Big Tech Companies]](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*hIqA_3mkWt9CLmJ4JXOGYw.jpeg)






