DEV Community

Mohana Kumar
Mohana Kumar

Posted on

Stop Using Callbacks! Learn JavaScript Promises Today

Introduction

Handling asynchronous operations is one of the most important parts of JavaScript. Before promises, developers relied heavily on callbacks, which often led to messy and hard-to-read code.

That’s where Promises come in.

A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation.


What is a Promise?

A Promise is like a guarantee that something will happen in the future.

Real-Life Analogy:

Imagine you ordered food online

  • Pending → Food is being prepared
  • Fulfilled → Food delivered
  • Rejected → Order canceled

Promise States

A Promise has three states:

  1. Pending → Initial state
  2. Fulfilled → Operation successful
  3. Rejected → Operation failed

Creating a Promise

You can create a Promise using the Promise constructor.

```javascript id="y9m9y5"
const myPromise = new Promise((resolve, reject) => {
let success = true;

if (success) {
resolve("Operation successful!");
} else {
reject("Operation failed!");
}
});




---

##  Consuming a Promise

You handle promises using `.then()` and `.catch()`.



```javascript id="b7y6cf"
myPromise
  .then((result) => {
    console.log(result);
  })
  .catch((error) => {
    console.log(error);
  });
Enter fullscreen mode Exit fullscreen mode

Promise Chaining

Promises allow chaining multiple async operations cleanly.

```javascript id="u5q7w2"
new Promise((resolve) => {
resolve(2);
})
.then((num) => {
return num * 2;
})
.then((num) => {
return num * 3;
})
.then((num) => {
console.log(num); // 12
});




---

##  Handling Errors

Errors can be handled using `.catch()`.



```javascript id="8j9k2x"
new Promise((resolve, reject) => {
  reject("Something went wrong!");
})
  .then((res) => console.log(res))
  .catch((err) => console.log(err));
Enter fullscreen mode Exit fullscreen mode

Promise vs Callback

Feature Callback Promise
Readability Hard (callback hell) Clean & structured
Error Handling Difficult Easy with .catch()
Chaining Not easy Easy

Why Use Promises?

✔ Avoid callback hell
✔ Better readability
✔ Easier error handling
✔ Cleaner async code


When to Use Promises

  • API calls
  • Database operations
  • File handling
  • Timers

Conclusion

  • Promises simplify asynchronous programming in JavaScript
  • They replace messy callbacks with clean, readable code

Top comments (0)