When I was a few years into my career, one of the concepts that really changed the way I wrote JavaScript was Promises. Before async/await, Promises were the go-to way to handle asynchronous operations. Even now, understanding them deeply is important because async/await is built on top of Promises.
A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation.
It can be in one of three states:
Pending → Initial state, neither fulfilled nor rejected.
Fulfilled → The operation completed successfully.
Rejected → The operation failed.
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("The operation was successful!");
} else {
reject("Something went wrong.");
}
});
myPromise
.then(result => console.log(result))
.catch(error => console.error(error));
Here’s what happens:
We create a new Promise.
If success is true → it resolves.
If success is false → it rejects.
.then() handles success.
.catch() handles failure.
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => console.log("Post:", data))
.catch(error => console.error("Error:", error));
fetch() returns a Promise.
We chain .then() calls to process the response.
.catch() handles errors (like network issues).
getUser()
.then(user => getPosts(user.id))
.then(posts => getComments(posts[0].id))
.then(comments => console.log(comments))
.catch(error => console.error(error));
This pattern avoids callback hell and makes async logic easier to follow.
Later, async/await came along, making Promises easier to read:
async function getData() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const data = await response.json();
console.log("Post:", data);
} catch (error) {
console.error("Error:", error);
}
}
getData();
But under the hood, async/await is still using Promises.
When I first learned Promises, it felt like a big leap from callbacks. Today, async/await makes things look simpler, but a strong grasp of Promises helps you understand how JavaScript really handles async operations.
If you’re new, start by writing a few examples with .then() and .catch(), then refactor them into async/await. That’s the best way to master it.