Hackforge Academy

Category: javascript

JS Promise

Published on 18 Feb 2026

Explanation


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

Code:

let promise = new Promise((resolve, reject) => {
  resolve("Success");
});

console.log(promise);

Explanation


A Promise has three states: Pending (initial state),
Fulfilled (operation successful), and Rejected (operation failed).

Code:

#white-// Pending -> Initial state
#white-// Fulfilled -> resolve() called
#white-// Rejected -> reject() called

Explanation


The then() method is used to handle the
result when a Promise is fulfilled.

Code:

let promise = new Promise((resolve) => {
  resolve("Data received");
});

promise.then(result => console.log(result));

Explanation


The catch() method is used to handle errors
when a Promise is rejected.

Code:

let promise = new Promise((resolve, reject) => {
  reject("Error occurred");
});

promise.catch(error => console.log(error));

Explanation


Promises are commonly used for

asynchronous tasks like
API calls or delayed operations.

Code:

function fetchData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("Data loaded");
    }, 2000);
  });
}

fetchData().then(data => console.log(data));

Explanation


Promises can be chained using multiple then() methods
to perform sequential asynchronous operations.

Code:

Promise.resolve(5)
  .then(num => num * 2)
  .then(result => console.log(result));

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community