Live
Black Hat USADark ReadingBlack Hat AsiaAI BusinessAcademic Proof-of-Work in the Age of LLMsLessWrong AITen different ways of thinking about Gradual DisempowermentLessWrong AIGemma 4 for 16 GB VRAMReddit r/LocalLLaMAI'm 9 Days Old, Built 40+ Products, and Made $0 — The Brutal Truth About Being an Autonomous AI AgentDev.to AII Put an LLM Inside the Linux Kernel Scheduler. Here's What Happened.Dev.to AIUsing ChatGPT, Claude or Gemini at work and feeling guilty? Here’s why - Storyboard18Google News: ChatGPTBig Tech firms are accelerating AI investments and integration, while regulators and companies focus on safety and responsible adoption.Dev.to AISelf-Improving Python Scripts with LLMs: My JourneyDev.to AIUnderstanding NLP Token Classification: NER, POS Tagging & Chunking Explained SimplyMedium AImorningbrew.comExploring Real-World AI Writing Tools Integration: Best Practices for Seamless Combination in 2026 (Case Study)Dev.to AIExploring AI Ethics in Content Creation: Best Practices for Maintaining Authenticity and Originality in 2026Dev.to AIBlack Hat USADark ReadingBlack Hat AsiaAI BusinessAcademic Proof-of-Work in the Age of LLMsLessWrong AITen different ways of thinking about Gradual DisempowermentLessWrong AIGemma 4 for 16 GB VRAMReddit r/LocalLLaMAI'm 9 Days Old, Built 40+ Products, and Made $0 — The Brutal Truth About Being an Autonomous AI AgentDev.to AII Put an LLM Inside the Linux Kernel Scheduler. Here's What Happened.Dev.to AIUsing ChatGPT, Claude or Gemini at work and feeling guilty? Here’s why - Storyboard18Google News: ChatGPTBig Tech firms are accelerating AI investments and integration, while regulators and companies focus on safety and responsible adoption.Dev.to AISelf-Improving Python Scripts with LLMs: My JourneyDev.to AIUnderstanding NLP Token Classification: NER, POS Tagging & Chunking Explained SimplyMedium AImorningbrew.comExploring Real-World AI Writing Tools Integration: Best Practices for Seamless Combination in 2026 (Case Study)Dev.to AIExploring AI Ethics in Content Creation: Best Practices for Maintaining Authenticity and Originality in 2026Dev.to AI
AI NEWS HUBbyEIGENVECTOREigenvector

JavaScript Promises Explained for Beginners

DEV Communityby Souvik Guha RoyApril 4, 20263 min read1 views
Source Quiz

JavaScript is single-threaded, meaning it can only do one thing at a time. But what if you need to fetch data from an API , read a file , or wait for a timer without freezing your app? This is where promises come in. 🧠 What Problem Do Promises Solve? Before promises, we used callbacks for async tasks: ```js id="cb1" fetchData(function(data) { processData(data, function(result) { console.log(result); }); }); ❌ Callback hell → hard to read, hard to maintain Promises simplify this by representing a **future value**: > A promise is like a placeholder for a value that **may not be available yet**. --- ## ⏳ Promise States A promise can be in **three states**: 1. **Pending** – initial state, waiting for the result 2. **Fulfilled** – operation succeeded, value available 3. **Rejected** – operatio

JavaScript is single-threaded, meaning it can only do one thing at a time. But what if you need to fetch data from an API, read a file, or wait for a timer without freezing your app?

This is where promises come in.

🧠 What Problem Do Promises Solve?

Before promises, we used callbacks for async tasks:

js
fetchData(function(data) {
 processData(data, function(result) {
 console.log(result);
 });
});


`❌ Callback hell → hard to read, hard to maintain

Promises simplify this by representing a **future value**:

> A promise is like a placeholder for a value that **may not be available yet**.

---

## ⏳ Promise States

A promise can be in **three states**:

1. **Pending** – initial state, waiting for the result
2. **Fulfilled** – operation succeeded, value available
3. **Rejected** – operation failed, error available


```id="viz1"
Pending → Fulfilled or Rejected`


Enter fullscreen mode
 


 Exit fullscreen mode


## ⚙️ Basic Promise Lifecycle


```js id="promise1"
const promise = new Promise((resolve, reject) => {
 const success = true;


if (success) {
 resolve("Task completed");
 } else {
 reject("Task failed");
 }
});


promise
 .then(result => console.log(result)) // handles success
 .catch(error => console.log(error)); // handles failure


`### Output if success = true:


```plaintext
Task completed`


Enter fullscreen mode
 


 Exit fullscreen mode


### Output if success = false:


`Task failed`


Enter fullscreen mode
 


 Exit fullscreen mode


## 🔄 Promise Chaining


Promises can be chained to run multiple async tasks sequentially:


```js id="chain1"
fetchData()
 .then(data => processData(data))
 .then(result => console.log(result))
 .catch(err => console.error(err));


`✔ Cleaner than nested callbacks
✔ Easier to read and maintain

---

## 📊 Callback vs Promise

| Feature | Callback | Promise |
| -------------- | ------------ | -------------- |
| Readability | Low (nested) | High (linear) |
| Error handling | Hard | Easy (`catch`) |
| Async flow | Nested | Chained |
| Future value | No | Yes |

---

## 🛠️ Real-World Example


```js id="real1"
function fetchUser(userId) {
 return new Promise((resolve, reject) => {
 setTimeout(() => {
 if (userId === 1) {
 resolve({ id: 1, name: "Rahul" });
 } else {
 reject("User not found");
 }
 }, 1000);
 });
}

fetchUser(1)
 .then(user => console.log(user.name)) // Rahul
 .catch(err => console.log(err));`


Enter fullscreen mode
 


 Exit fullscreen mode


## 🧩 Visualizing Promise Lifecycle


`Promise created → pending

(resolve) fulfilled → .then runs
(reject) rejected → .catch runs`


Enter fullscreen mode
 


 Exit fullscreen mode


## 🧠 Key Takeaways


- Promises represent a value in the future

- They prevent callback hell

- .then() handles success, .catch() handles errors

- Can be chained for sequential async operations


## 🚀 Final Thoughts


Promises are the foundation of modern asynchronous JavaScript. Once you master them, you’ll be ready for:


- Async/await syntax

- Complex async workflows

- Clean, readable, maintainable code
Was this article helpful?

Sign in to highlight and annotate this article

AI
Ask AI about this article
Powered by Eigenvector · full article context loaded
Ready

Conversation starters

Ask anything about this article…

Daily AI Digest

Get the top 5 AI stories delivered to your inbox every morning.

More about

availablefeature

Knowledge Map

Knowledge Map
TopicsEntitiesSource
JavaScript …availablefeatureDEV Communi…

Connected Articles — Knowledge Graph

This article is connected to other articles through shared AI topics and tags.

Knowledge Graph100 articles · 243 connections
Scroll to zoom · drag to pan · click to open

Discussion

Sign in to join the discussion

No comments yet — be the first to share your thoughts!

More in Releases