Live
β€’Black Hat USAAI Businessβ€’Black Hat AsiaAI Businessβ€’We Shipped a RAG Chatbot to 500 Enterprise Tenants. Here's What Actually Broke First.Dev.to AIβ€’Humans and the retain of control in a world where AI thinks and decides alongside usDev.to AIβ€’Insights from GDPS 2026: Enterprise Agents, AI Native, and One-Person CompaniesDev.to AIβ€’Estimates on the generalization error of Physics Informed Neural Networks(PINNs) for approximating PDEsDev.to AIβ€’Benyar Men's Watches SA and Lige Men's Watches South Africa: Bold Styles for SA MenDev.to AIβ€’5 Signs You're Ready to Build Your SaaS (And 3 Signs You're Not)Dev.to AIβ€’Am I the baddie?lesswrong.comβ€’Liable sourcesMedium AIβ€’Measure twice, code once: Conductor for Claude CodeMedium AIβ€’Beyond the Bot: How AI is Actually Changing the Way We WorkMedium AIβ€’Autoregression & Next-Token PredictionMedium AIβ€’I Tried 5 AI Side Hustles for 7 Days β€” Here’s What Actually Made Me Money (India 2026)Medium AIβ€’Black Hat USAAI Businessβ€’Black Hat AsiaAI Businessβ€’We Shipped a RAG Chatbot to 500 Enterprise Tenants. Here's What Actually Broke First.Dev.to AIβ€’Humans and the retain of control in a world where AI thinks and decides alongside usDev.to AIβ€’Insights from GDPS 2026: Enterprise Agents, AI Native, and One-Person CompaniesDev.to AIβ€’Estimates on the generalization error of Physics Informed Neural Networks(PINNs) for approximating PDEsDev.to AIβ€’Benyar Men's Watches SA and Lige Men's Watches South Africa: Bold Styles for SA MenDev.to AIβ€’5 Signs You're Ready to Build Your SaaS (And 3 Signs You're Not)Dev.to AIβ€’Am I the baddie?lesswrong.comβ€’Liable sourcesMedium AIβ€’Measure twice, code once: Conductor for Claude CodeMedium AIβ€’Beyond the Bot: How AI is Actually Changing the Way We WorkMedium AIβ€’Autoregression & Next-Token PredictionMedium AIβ€’I Tried 5 AI Side Hustles for 7 Days β€” Here’s What Actually Made Me Money (India 2026)Medium AI
AI NEWS HUBbyEIGENVECTOREigenvector

JavaScript Promises Explained for Beginners

DEV Communityby Souvik Guha RoyApril 4, 20263 min read0 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 Β· 215 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