Promises & Promise Chaining Kya Hote Hain – Promises & Promise Chaining in JavaScript

Promises & Promise Chaining Kya Hote Hain?

1. Promises :

JavaScript mein Promises ek aise object hote hain jo asynchronous operations ka result represent karte hain — ya to success (resolve) ya failure (reject). Jab hum kisi asynchronous task jaise API call, file read ya setTimeout ke baad kuch karna chahte hain, tab Promise use kiya jata hai.

Ek Promise teen state mein ho sakta hai: Pending (initial state), Fulfilled (operation successful), ya Rejected (operation failed).

Hum .then() ka use karke fulfilled result handle karte hain, aur .catch() se errors.

Iska fayda ye hai ki code readable aur manageable ban jata hai, especially jab multiple asynchronous tasks ho. Promises callback hell ko avoid karne ke liye bhi useful hote hain. Yeh modern JavaScript ka ek important part hai.

Easy Words Mein:

Jab hum koi kaam karte hain jo time leta hai (jaise server se data lana), toh JavaScript us kaam ko turant complete nahi karti. Wo keh deti hai – “Main promise karti hoon ki result baad mein dungi.”

  • Pending – Promise abhi complete nahi hua (waiting)
  • Fulfilled (Resolved) – Kaam successful ho gaya
  • Rejected – Kaam fail ho gaya (error aaya)
let meraPromise = new Promise(function(resolve, reject) {
  let kaamHoGaya = true;

  if (kaamHoGaya) {
    resolve("Kaam ho gaya!");
  } else {
    reject("Kaam fail ho gaya.");
  }
});

resolve() ⇒ Jab kaam sahi se complete ho jaye
reject() ⇒ Jab kaam mein error aaye

Promise Consume karna – then() aur catch() se:

meraPromise
  .then(function(result) {
    console.log("Success:", result);
  })
  .catch(function(error) {
    console.log("Error:", error);
  });

Promise Chaining :

Promise chaining ek technique hai JavaScript mein jahan hum multiple asynchronous operations ko ek ke baad ek perform karte hain, bina callback hell ke. Jab ek promise resolve hota hai, .then() method use karke hum agla kaam define karte hain. Har .then() ek naya promise return karta hai, jise next .then() handle karta hai. Isse code readable aur manageable ban jaata hai. Agar chain mein kahin error aata hai, toh usse .catch() se handle kiya ja sakta hai. Yeh approach asynchronous logic ko sequentially execute karne ke liye bahut useful hoti hai. Example: fetchData().then(processData).then(displayData).catch(handleError); — yahaan har step agle par depend karta hai, aur errors bhi easily manage ho jaate hain.

 Example:

  1. Server se user ka data lana hai
  2. Uske baad us user ke orders lana hai
  3. Uske baad us orders ka total calculate karna hai

Yeh sab kaam ek ke baad ek hone chahiye – yahi hai Promise chaining.

getUser()
  .then(function(user) {
    console.log("User mila:", user);
    return getOrders(user.id);
  })
  .then(function(orders) {
    console.log("Orders mile:", orders);
    return calculateTotal(orders);
  })
  .then(function(total) {
    console.log("Total amount:", total);
  })
  .catch(function(error) {
    console.log("Error aaya:", error);
  });
  • Har .then() ke andar hum agla async kaam karte hain
  • Ye ek chain ban jaata hai
  • Agar kahin bhi error aaye, wo directly .catch() mein chala jaata hai

Promise Chaining ke Fayde:

JavaScript me Promise Chaining ek powerful technique hai jo asynchronous code ko manageable aur readable banata hai. Jab ek promise complete ho jata hai, to .then() method ka use karke hum next task define kar sakte hain. Is process ko chaining kehte hain. Fayda ye hota hai ki multiple asynchronous operations ko sequentially perform kiya ja sakta hai bina callback hell me fase. Isse code structured, clean aur error handling easy hoti hai. Har .then() ek naya promise return karta hai, jisse next step easily connect ho jata hai. Agar koi error aata hai, to .catch() method se usse efficiently handle kiya ja sakta hai. Overall, promise chaining se asynchronous flow simple aur logical ban jata hai.

Summary :

  • Promise ek async operation ka future result represent karta hai.
  • Teen state: Pending, Resolved, Rejected
  • .then() se success handle hota hai
  • .catch() se error handle hota hai
  • Promise chaining ek ke baad ek kaam ko sequence mein karne ka method hai
  • Ye code ko clean, readable aur error-proof banata hai

Async/Await in JavaScript :

async/await JavaScript ka ek modern syntax hai jo asynchronous code ko likhne ka ek easy aur readable tareeka deta hai. Ye code ko synchronous jaise dikhata hai, lekin andar se wo asynchronous hi hota hai.

Asynchronous ka Concept:

JavaScript ek single-threaded language hai – iska matlab ek time pe ek hi kaam karta hai.

Lekin jab kisi kaam mein zyada time lagta hai (jaise API se data fetch karna, file read karna, image load karna), to hum usko asynchronous bana dete hain taki JavaScript baki kaam karta rahe aur wo time-consuming kaam background mein chalta rahe.

Asynchronous code likhne ke liye pehle log callback functions aur promises ka use karte the. Lekin unka syntax complex ho jaata tha (callback hell ya promise chaining).

Async Function Kya hota hai?

async function meraFunction() {
  return "Hello";
}

Yahaan pe meraFunction() promise return karega jo resolve hoga “Hello” se.

Await Kya karta hai?

await keyword kisi bhi promise ke aage lagta hai, aur JavaScript ko bolta hai: “Ruko, jab tak yeh promise resolve nahi ho jaata, tab tak next line pe mat jao.”

await ka use sirf async function ke andar hi ho sakta hai.

Example without async/await:

fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

Yahaan promise chaining use ki gayi hai. Agar chaining lambi ho jaaye to code complex lagta hai.

Same example with async/await:

async function getData() {
  try {
    const response = await fetch("https://api.example.com/data");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Error aaya:", error);
  }
}

Yahaan same kaam hua, lekin code zyada clean aur readable hai.

Important Points:

  • 1. Async function always returns a promise:
    async function foo() {
      return 5;
    }
    // returns Promise.resolve(5)
    
  • 2. Await ke bina async ka koi matlab nahi: Sirf async lagana kaafi nahi, use ke sath await bhi hona chahiye.
  • 3. Await pauses execution: Jab tak promise resolve nahi hota, await us async function ko pause kar deta hai.
  • 4. Try-Catch se error handle karo: Async functions ke andar error handle karne ke liye try-catch ka use karo.

 Example:

  1. Tum order karte ho (asynchronous kaam start)
  2. Tum TV dekhte ho jab tak pizza aata hai (baki kaam chalu hai)
  3. Pizza aata hai – tum usko accept karte ho (promise resolve)
  4. Tum khaana shuru karte ho (next action)

Async/await yeh kehta hai: “Ruko, jab tak pizza nahi aata, main TV nahi dekhunga.”

Nested Await – Multiple await ek function mein:

async function process() {
  const user = await getUser();
  const posts = await getPosts(user);
  const comments = await getComments(posts[0]);
  console.log(comments);
}

Conclusion:

Async/await JavaScript mein asynchronous kaam ko easy aur readable banane ka modern tareeka hai.

  • Ye Promises par based hai
  • Code ko synchronous jaisa banata hai
  • await sirf async function ke andar kaam karta hai
  • Always use try-catch for error handling

Async/await se aapka code clean, manageable, aur developer-friendly ho jaata hai.

Quiz: Test Your Knowledge on Promises & Promise Chaining in JavaScript

Bonus: Practical Application!

Aaj hi JavaScript Promises & Promise Chaining ka use karke asynchronous tasks handle karna sikhiye!

 Promises & chaining ka sahi tareeke se samajhne ke liye .then(), .catch(), .finally() jaise methods ka upayog karein, aur ek real-world example create karke asynchronous code ko simplify karne ka anubhav lein.

Leave a Reply