📘 Lesson  ·  Lesson 43

Promises

Promises

What a Promise Is

A Promise is an object representing a value that isn't available YET, but will be at some point — either a result, or an error. Think of ordering food at a counter: you're handed a token. The food isn't ready, but the token PROMISES that eventually you'll get either your meal (success) or an apology that it's sold out (failure). Meanwhile, you're free to do other things. Promises solved callback hell by letting you attach "what to do next" in a flat chain instead of nesting functions inside functions.

The Three States

StateMeaning
pendingStill working — no result yet (the initial state)
fulfilledSucceeded — a value is available
rejectedFailed — an error is available
Every Promise begins as pending and then settles exactly once — into either fulfilled (it worked, here's the value) or rejected (it failed, here's the error). Once settled, it never changes again. This one-way, one-time transition is what makes Promises predictable. Your job as a developer is to say what should happen in each case: .then() handles fulfilment, .catch() handles rejection.

then and catch — handling the result

fetch("https://api.example.com/students")     // returns a Promise
    .then(response => response.json())        // runs on success → another Promise
    .then(data => {
        console.log(data);                    // finally, the actual data
    })
    .catch(error => {
        console.log("Something went wrong:", error);   // runs on failure
    })
    .finally(() => {
        console.log("Done either way");       // always runs
    });
.then(callback) runs when the Promise fulfils, receiving the value. .catch(callback) runs if anything in the chain rejects, receiving the error. .finally() runs either way — perfect for hiding a loading spinner. Notice fetch(): it's the built-in function for requesting data from a server, and it returns a Promise. This exact pattern — fetch, .then, .json(), .then, .catch — is how the web has fetched data for years, and it's the foundation of the AJAX tutorial ahead.

Chaining — flat, not nested

// Callback hell (nested pyramid):
getUser(1, user => {
    getOrders(user.id, orders => {
        getDetails(orders[0].id, details => { console.log(details); });
    });
});

// The same thing with Promises — a FLAT chain:
getUser(1)
    .then(user => getOrders(user.id))       // return a Promise...
    .then(orders => getDetails(orders[0].id))  // ...and the next .then waits for it
    .then(details => console.log(details))
    .catch(err => console.log("Failed:", err));   // ONE catch for the whole chain
This is the payoff: each .then() can RETURN another Promise, and the next .then() waits for it. The pyramid becomes a flat, readable, top-to-bottom sequence of steps. And errors anywhere in the chain fall through to a single .catch() at the end — compare that to callback hell, where every level needed its own error handling. The rule to remember: always return the Promise inside a .then(), or the chain won't wait for it.

Creating a Promise and Promise.all

// Making your own Promise:
const wait = (ms) => new Promise((resolve, reject) => {
    if (ms < 0) reject("Negative time!");    // failure
    setTimeout(() => resolve("Done!"), ms);  // success, after a delay
});

wait(1000).then(msg => console.log(msg));    // "Done!" after 1 second

// Run several Promises together and wait for ALL of them:
Promise.all([fetch(url1), fetch(url2)])
    .then(results => console.log("Both finished"));
You rarely need to create Promises by hand — most come from built-in functions like fetch. But it's worth seeing: new Promise((resolve, reject) => {...}) gives you two functions; call resolve(value) on success or reject(error) on failure. Far more useful in practice is Promise.all(), which takes an array of Promises and waits for every one to finish — ideal for loading several things at once, in parallel rather than one after another.

Exam Corner

Q: What is a Promise? An object representing a value that will be available in the future — either a result or an error.

Q: Name the three states of a Promise. pending, fulfilled, rejected.

Q: What do then() and catch() do? then runs on success with the value; catch runs on failure with the error.

Q: How do Promises solve callback hell? They allow a flat chain of .then() calls with one shared .catch(), instead of nesting.

Q: What does Promise.all() do? Waits for an array of Promises to all finish.

Promise क्या है

Promise ऐसा object है जो उस value को दर्शाता है जो ABHI उपलब्ध नहीं, पर किसी समय होगी — या तो नतीजा, या error. Counter पर खाना order करना सोचिए: आपको token मिलता है. खाना तैयार नहीं, पर token VAADA करता है कि आखिरकार आपको या तो आपका भोजन (सफलता) मिलेगा या माफी कि वह खत्म हो गया (विफलता). इस बीच, आप दूसरे काम करने को स्वतंत्र हैं. Promises ने callback hell हल किया आपको "आगे क्या करना है" को functions के अंदर functions nest करने के बजाय समतल chain में जोड़ने देकर.

तीन States

Stateमतलब
pendingअभी काम चल रहा — कोई नतीजा नहीं (शुरुआती state)
fulfilledसफल — value उपलब्ध है
rejectedविफल — error उपलब्ध है
हर Promise pending से शुरू होकर ठीक एक बार settle होता है — या तो fulfilled (चल गया, यह रही value) या rejected (fail हुआ, यह रहा error). एक बार settle होने पर, यह फिर कभी नहीं बदलता. यह एकतरफा, एक-बार का बदलाव ही Promises को predictable बनाता है. Developer के रूप में आपका काम बताना है हर मामले में क्या होना चाहिए: .then() fulfilment संभालता है, .catch() rejection.

then और catch — नतीजा संभालना

fetch("https://api.example.com/students")     // Promise lautata hai
    .then(response => response.json())        // safalta par chalta → aur Promise
    .then(data => {
        console.log(data);                    // aakhirkar, asli data
    })
    .catch(error => {
        console.log("Kuch galat hua:", error);   // vifalta par chalta
    })
    .finally(() => {
        console.log("Kaise bhi ho, ho gaya");  // hamesha chalta
    });
.then(callback) Promise fulfil होने पर चलता है, value पाते. .catch(callback) chain में कुछ भी reject हो तो चलता है, error पाते. .finally() दोनों हाल में चलता है — loading spinner छुपाने के लिए perfect. fetch() ध्यान दीजिए: यह server से data मांगने का built-in function है, और यह Promise लौटाता है. यही pattern — fetch, .then, .json(), .then, .catch — सालों से web ने data ऐसे ही लाया है, और यह आगे आने वाले AJAX tutorial की नींव है.

Chaining — समतल, nested नहीं

// Callback hell (nested pyramid):
getUser(1, user => {
    getOrders(user.id, orders => {
        getDetails(orders[0].id, details => { console.log(details); });
    });
});

// Vahi cheez Promises se — SAMTAL chain:
getUser(1)
    .then(user => getOrders(user.id))       // Promise return karo...
    .then(orders => getDetails(orders[0].id))  // ...aur agla .then uska intezaar karta
    .then(details => console.log(details))
    .catch(err => console.log("Failed:", err));   // poore chain ke liye EK catch
यही फायदा है: हर .then() दूसरा Promise RETURN कर सकता है, और अगला .then() उसका इंतज़ार करता है. Pyramid समतल, पढ़ने योग्य, ऊपर-से-नीचे कदमों का क्रम बन जाता है. और chain में कहीं भी errors अंत में एक .catch() तक गिरते हैं — callback hell से तुलना कीजिए, जहां हर स्तर को अपनी error handling चाहिए थी. याद रखने का नियम: .then() के अंदर हमेशा Promise return कीजिए, वरना chain उसका इंतज़ार नहीं करेगी.

Promise बनाना और Promise.all

// Apna Promise banana:
const wait = (ms) => new Promise((resolve, reject) => {
    if (ms < 0) reject("Negative time!");    // vifalta
    setTimeout(() => resolve("Done!"), ms);  // safalta, delay ke baad
});

wait(1000).then(msg => console.log(msg));    // 1 second baad "Done!"

// Kai Promises saath chalao aur SAB ka intezaar karo:
Promise.all([fetch(url1), fetch(url2)])
    .then(results => console.log("Dono khatm"));
आपको शायद ही हाथ से Promises बनाने पड़ते हैं — ज़्यादातर fetch जैसे built-in functions से आते हैं. पर देखना लायक है: new Promise((resolve, reject) => {...}) आपको दो functions देता है; सफलता पर resolve(value) या विफलता पर reject(error) call कीजिए. व्यवहार में कहीं ज़्यादा उपयोगी है Promise.all(), जो Promises की array लेकर हर एक के खत्म होने का इंतज़ार करता है — कई चीज़ें एक साथ load करने को आदर्श, एक के बाद एक के बजाय समानांतर.

Exam Corner

Q: Promise क्या है? ऐसा object जो भविष्य में उपलब्ध होने वाली value दर्शाता है — या तो नतीजा या error.

Q: Promise की तीन states बताइए. pending, fulfilled, rejected.

Q: then() और catch() क्या करते हैं? then सफलता पर value के साथ चलता; catch विफलता पर error के साथ.

Q: Promises callback hell कैसे हल करते हैं? वे nesting के बजाय एक साझा .catch() के साथ .then() calls की समतल chain देते हैं.

Q: Promise.all() क्या करता है? Promises की array के सब खत्म होने का इंतज़ार करता है.
← Back to JavaScript Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

इस पेज का code यहाँ तैयार है — बदलिए और तुरंत नतीजा देखिए. कुछ install किए बिना.
👁 Live Preview
सब कुछ आपके browser में ही चलता है — कोई server, कोई signup नहीं. JavaScript का console.log देखने के लिए F12 दबाइए.