JavaScript Promises & Promise Chaining Kya Hote Hain?

Asynchronous operations ko cleanly aur efficiently handle karna sikhein.

1. Promises Kya Hain?

JavaScript mein Promise ek special object hai jo ek asynchronous operation ke future result ko represent karta hai. Jab aap koi aisa kaam karte hain jisme time lagta hai (jaise server se data fetch karna), toh JavaScript turant result nahi de sakta. Iski jagah, woh aapko ek "promise" de deta hai ki jab kaam poora hoga, toh woh aapko result (ya error) dega.

Promise ki Teen States

Ek Promise hamesha in teen states me se ek me hota hai:

  • Pending: Initial state, operation abhi chal raha hai.
  • Fulfilled (Resolved): Operation successfully complete ho gaya.
  • Rejected: Operation fail ho gaya.

Promise Kaise Banayein?

const meraPromise = new Promise(function(resolve, reject) {
  let kaamHoGaya = true;

  if (kaamHoGaya) {
    // Agar kaam successful hai, toh resolve() call karein
    resolve("Kaam safaltapurvak ho gaya!");
  } else {
    // Agar error hai, toh reject() call karein
    reject("Kaam fail ho gaya.");
  }
});

Promise ko Use Karna (.then & .catch)

Promise ke result ko handle karne ke liye hum .then() (success ke liye) aur .catch() (failure ke liye) methods ka use karte hain.

meraPromise
  .then(function(successMessage) {
    console.log(successMessage); // "Kaam safaltapurvak ho gaya!"
  })
  .catch(function(errorMessage) {
    console.error(errorMessage);
  });

2. Promise Chaining

Promise Chaining ek powerful technique hai jisse hum multiple asynchronous operations ko ek sequence me perform kar sakte hain, bina "callback hell" me phase. Har .then() ek naya promise return karta hai, jise hum agle .then() se chain kar sakte hain.

Imagine karein, aapko pehle user ka data fetch karna hai, fir uske orders, aur fir un orders ka total calculate karna hai. Yeh sab kaam ek ke baad ek hone chahiye.

getUser()
  .then(user => {
    console.log("User mila:", user);
    return getOrders(user.id); // Naya promise return karein
  })
  .then(orders => {
    console.log("Orders mile:", orders);
    return calculateTotal(orders); // Ek aur promise
  })
  .then(total => {
    console.log("Total amount:", total);
  })
  .catch(error => {
    console.error("Chain me kahin error aayi:", error);
  });

Promise Chaining ke Fayde

  • Readability: Code clean aur easy-to-read rehta hai.
  • Maintainability: Logic ko follow karna aur debug karna aasan hota hai.
  • Error Handling: Chain ke end me ek single .catch() block poori chain ke kisi bhi error ko handle kar sakta hai.

3. Async/Await: A Modern Alternative

`async/await` Promises ke upar ek modern syntax hai jo asynchronous code ko synchronous jaisa dikhata hai. Isse code aur bhi clean ho jaata hai.

Upar diye gaye chaining example ko `async/await` se aise likh sakte hain:

async function processUserOrder() {
  try {
    const user = await getUser();
    console.log("User mila:", user);

    const orders = await getOrders(user.id);
    console.log("Orders mile:", orders);

    const total = await calculateTotal(orders);
    console.log("Total amount:", total);
  } catch (error) {
    console.error("Error aaya:", error);
  }
}

processUserOrder();

Yeh approach complex asynchronous logic ko bohot simple bana deti hai.

Key Takeaways

  • Promise ek asynchronous operation ke future result ka placeholder hai.
  • Promises ki teen states hoti hain: Pending, Fulfilled, aur Rejected.
  • Success ko .then() se aur errors ko .catch() se handle kiya jaata hai.
  • Promise Chaining se multiple asynchronous tasks ko sequentially manage kiya jaata hai.
  • `async/await` promise-based code likhne ka sabse modern aur readable tarika hai.
Bonus: Practical Application!
Ab in concepts ko practically use karke dekhein.

Ek Promise banayein jo 1 second ke baad "Task Complete!" message ke saath resolve ho. Fir `.then()` ka use karke us message ko console me print karein.

Practice in JS Editor
Test Your Knowledge!
Kya aap Promises aur Promise Chaining ke baare mein seekh chuke hain? Chaliye dekhte hain!

Apni knowledge test karne ke liye is quick quiz ko dein.

Start Quiz