DEV Community

PONVEL M
PONVEL M

Posted on

Understanding Promises in JavaScript

Handling Asynchronous Operations the Right Way

JavaScript is single-threaded, but it can handle asynchronous operations like API calls, file reading, and timers.
To manage these async tasks efficiently, JavaScript provides Promises.

πŸ”Ή What is a Promise in JavaScript?

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

In simple words:
πŸ‘‰ β€œI promise to return a value later β€” either success or error.”

πŸ”Ή Why Do We Need Promises?

Before Promises, JavaScript used callbacks, which caused problems like:

❌ Callback Hell
❌ Hard-to-read code
❌ Difficult error handling

Promises solve these problems by providing:

  • Cleaner syntax
  • Better error handling
  • Chainable operations

πŸ”Ή Promise States

A Promise can be in one of three states:

  • Pending – Initial state (waiting)
  • *Fulfilled *– Operation completed successfully
  • Rejected – Operation failed

Once a promise is fulfilled or rejected, it is settled and cannot change again.

πŸ”Ή Creating a Promise

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

if (success) {
resolve("Promise resolved successfully");
} else {
reject("Promise rejected");
}
});

  • resolve() β†’ success result
  • reject() β†’ error result`

πŸ”Ή Consuming a Promise

`Using .then() and .catch()
myPromise
.then(result => {
console.log(result);
})
.catch(error => {
console.log(error);
});

  • .then() β†’ handles success
  • .catch() β†’ handles error`

πŸ”Ή Promise Chaining

Promises can be chained to **perform multiple async tasks **sequentially.

fetchData()
.then(data => processData(data))
.then(result => displayResult(result))
.catch(error => console.log(error));

βœ… Avoids callback hell
βœ… Improves readability

Top comments (0)