Understanding JavaScript Promises-Part 1
Understanding JavaScript Promises
JavaScript is a powerful language that allows developers to create dynamic and interactive web applications.
One of its key features is the ability to work with asynchronous code — enabling JavaScript to perform multiple tasks simultaneously without blocking execution.
However, working with asynchronous code can be tricky, especially when dealing with callbacks.
Callbacks can quickly lead to callback hell, making code harder to read and maintain.
This is where JavaScript Promises come in.
What are JavaScript Promises?
JavaScript promises provide a cleaner, more organized way to handle asynchronous code.
They let developers write more readable and maintainable code by treating asynchronous operations in a more synchronous-like style.
A promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
A promise can be in one of three states:
- Pending → Initial state, the operation hasn’t completed yet.
- Fulfilled → The operation completed successfully (a value is available).
- Rejected → The operation failed (an error is available).
Creating a Promise
We use the Promise constructor to create a promise.
It takes a function with two arguments: resolve and reject.
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise resolved!');
}, 1000);
});
Here, setTimeout simulates a 1-second async task.
Once completed, it calls resolve with "Promise resolved!".
Consuming a Promise
We consume a promise using .then() and .catch().
myPromise
.then((message) => {
console.log(message);
})
.catch((error) => {
console.error(error);
});
.then() → Handles the fulfilled value.
.catch() → Handles any errors if rejected.
Chaining Promises
One of the most powerful features of promises is chaining, allowing multiple async tasks to run in sequence.
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise 1 resolved!');
}, 1000);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise 2 resolved!');
}, 2000);
});
promise1
.then((message) => {
console.log(message);
return promise2;
})
.then((message) => {
console.log(message);
})
.catch((error) => {
console.error(error);
});
First promise resolves after 1 second.
Its .then() returns the second promise.
The next .then() waits for and logs the result of the second promise.
.catch() handles errors if any step fails.
Conclusion
JavaScript promises are a powerful tool for handling async code in a more synchronous manner. They improve readability, maintainability, and allow chaining of operations.
✅ By creating, consuming, and chaining promises, developers can write cleaner and more efficient async code.
👉 Check out PART-2 of this series to dive even deeper!