DEV Community

Obada
Obada

Posted on

Promises in JavaScript

What is a Promise?

A promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Think of it like a placeholder for a value that will arrive in the future.

States of a Promise

A promise can be in one of three states:

  1. Pending - initial state, not fulfilled or rejected.
  2. Fulfilled - operation completed successfully.
  3. Rejected - operation failed.

Basic Syntax


const promise = new Promise((resolve, reject) => {
// async operation here
if (/* everything good */) {
resolve("Success!");
} else {
reject("Something went wrong.");
}
});

Consuming a Promise


promise
.then((result) => {
console.log(result); // "Success!"
})
.catch((error) => {
console.error(error); // "Something went wrong."
})
.finally(() => {
console.log("Done");
});

.then() is called when the promise is fulfilled.
.catch() is called when the promise is rejected.
.finally() runs regardless of success or failure.

Real Example: Using fetch


fetch('https://api.example.com/data')
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error('Error:', error));

Why Use Promise?

Before promises, we used callbacks, which could lead to "callback hell", deeply nested functions that are hard to read and maintain.

Promises solve that by:

  • Making code more readable

  • Making error handling easier

  • Chaining operations

Promises in JavaScript - a very important topic for writing clean, modern asynchronous code.

Top comments (0)