सामग्री पर जाएँ

लेसन 43 · Asynchronous Programming

async/await के Patterns

Node.js में async/await में महारत पाएँ: क्रमिक बनाम समानांतर await, try/catch, loops और forEach के जाल, top-level await, async stack traces और आम गलतियाँ।

async और await से आप ऐसा asynchronous कोड लिख सकते हैं जो आम synchronous कोड जैसा पढ़ा जाता है। async फ़ंक्शन (function) हमेशा एक प्रॉमिस (promise) लौटाता है, और await उस फ़ंक्शन को (पूरे प्रोग्राम को नहीं) तब तक रोकता है जब तक प्रॉमिस settle न हो जाए। जब वह रुका होता है, event loop बाकी सब कुछ चलाता रहता है। यह एक वाक्य मन में बैठ जाए, तो async कोड का ज़्यादातर उलझाने वाला व्यवहार अनुमान लगाने लायक हो जाता है।

यह lesson patterns के बारे में है: काम कब एक के बाद एक चलाएँ और कब साथ-साथ, errors कैसे व्यवहार करते हैं, forEach और await का मेल क्यों नहीं बैठता, वे गलतियाँ जो चुपचाप bugs पैदा करती हैं, और async stack traces debugging में कैसे मदद करते हैं। यहाँ सब कुछ ES modules में है, जहाँ await file के top level पर भी काम करता है।

एक उदाहरण में बुनियादी बातें

async फ़ंक्शन हर हाल में प्रॉमिस लौटाता है: वह value लौटाए तो प्रॉमिस उसी के साथ fulfill होता है; वह throw करे तो प्रॉमिस reject होता है। await प्रॉमिस की value खोलकर देता है, या ठीक उसी लाइन पर उसका rejection reason throw करता है।

Node.js async functions प्रॉमिस लौटाते हैं

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

दो छोटी बातें। async फ़ंक्शन की body अपने पहले await तक synchronous रूप से चलती है, इसलिए पहले await से पहले के side effects कॉल करते ही तुरंत होते हैं। और non-promise को await करना allowed है, पर बेमतलब; इससे बस एक बार microtask queue को मौका मिलता है।

क्रमिक (sequential) बनाम समानांतर (parallel)

await के साथ performance की सबसे आम गलती है अनजाने में स्वतंत्र कामों को एक-एक कदम करके चलाना। अगर operation B को operation A का नतीजा नहीं चाहिए, तो पहले दोनों शुरू करें और बाद में await करें।

Node.js क्रमिक awaits बनाम Promise.all

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

log में क्रमिक वाला start A, end A, start B, end B दिखाता है। समानांतर वाले में पहले दोनों start दिखते हैं, और end B, end A से पहले आता है क्योंकि B तेज़ है। कुल समय "A + B" से घटकर "दोनों में से धीमे वाले" जितना रह जाता है। समानांतर रूप लिखने का दूसरा तरीका है पहले प्रॉमिस शुरू करना और बाद में उन्हें await करना:

NODE
const userPromise = loadUser(id);      // अभी शुरू होता है
const ordersPromise = loadOrders(id);  // यह भी अभी शुरू होता है
const user = await userPromise;
const orders = await ordersPromise;

इस रूप में सावधानी रखें। अगर आप अभी userPromise का इंतज़ार कर रहे हैं और ordersPromise reject हो जाए, तो अभी तक उस पर किसी ने handler नहीं लगाया है, और Node unhandled rejection की सूचना दे सकता है। Promise.all हर चीज़ पर तुरंत handlers लगा देता है, इसलिए वही सुरक्षित डिफ़ॉल्ट है।

मोटा नियम: क्रम से await तभी करें जब किसी कदम को पिछले कदम का नतीजा चाहिए। वरना स्वतंत्र कदमों को Promise.all से (या आंशिक failure चल सकती हो तो Promise.allSettled से) एक समूह में रखें।

try/catch/finally से error handling

await rejection reason को throw करता है, इसलिए साधारण try/catch/finally asynchronous कदमों के पार भी काम करता है। callbacks की तुलना में पढ़ने की आसानी में यह सबसे बड़ी जीत है।

Node.js await के साथ try, catch और finally

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

try के अंदर return await query(...) पर ध्यान दें। await के बिना फ़ंक्शन तुरंत pending प्रॉमिस लौटा देता, try block से बाहर निकल जाता, finally query पूरी होने से पहले चल जाता, और rejection catch को पूरी तरह छोड़ देता। try block के अंदर आप जो लौटाते हैं, उसे हमेशा await करें। try के बाहर return promise और return await promise एक-सा व्यवहार करते हैं (दूसरे में थोड़ी-सी अतिरिक्त लागत है और stack trace ज़्यादा साफ़ होता है)।

कई तरह के errors पकड़ना

जब अलग-अलग failures पर अलग-अलग प्रतिक्रिया चाहिए, तो err.name, err.code जाँचें या instanceof इस्तेमाल करें। जो आपको समझ न आए, उसे दोबारा throw करें:

NODE
try {
  await doWork();
} catch (err) {
  if (err.code === 'ENOENT') {
    console.log('file missing, using defaults');
  } else {
    throw err; // यह हमारा नहीं: फ़ैसला किसी और को करने दें
  }
}

Loops और await

for...of या for लूप (loop) के अंदर await लूप को रोकता है, जिससे आपको भरोसेमंद क्रमिक processing मिलती है। जाल forEach, map, filter और इनके साथियों में है: वे हर item के लिए आपका फ़ंक्शन कॉल करते हैं, और async callback ऐसा प्रॉमिस लौटाता है जिसे method अनदेखा कर देता है।

Node.js forEach इंतज़ार नहीं करता

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

पहली लाइन खाली array दिखाती है, जो सबूत है कि forEach ने इंतज़ार नहीं किया। हल:

  • for...of + await जब क्रम मायने रखता हो, हर कदम पिछले पर निर्भर हो, या आपको किसी service पर ज़्यादा बोझ नहीं डालना हो।
  • map + Promise.all जब सब कुछ एक साथ चल सकता हो। हज़ारों items के लिए यह एक साथ बहुत ज़्यादा हो सकता है; सीमाएँ लगाने के लिए Concurrency Control and Queues देखें।
  • reduce संभव है, पर पढ़ने में कठिन; लूप को प्राथमिकता दें।

for await...of किसी async iterable (stream या async generator) पर लूप चलाता है और हर value को await करता है, जैसा Async Iterators and Generators में बताया गया है।

Node.js async source पर for await

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Top-level await

ES मॉड्यूल (module) में (हमारा editor आपका कोड इसी रूप में चलाता है; कोई भी .mjs file या "type": "module" वाला project भी ऐसा ही है) आप किसी फ़ंक्शन के बाहर भी await इस्तेमाल कर सकते हैं। मॉड्यूल बस अपना evaluation पूरा करने से पहले इंतज़ार करता है। यह scripts और configuration load करने के लिए बढ़िया है, और आपके उदाहरण छोटे करता है। दो कीमतें याद रखें: किसी धीमी चीज़ का await करने वाला मॉड्यूल उसे import करने वाली हर चीज़ को देर कराता है, और CommonJS files में top-level await एक syntax error है (वहाँ कोड को async फ़ंक्शन में लपेटें)।

आम गलतियाँ

await करना भूल जाना

await छूट जाए तो जहाँ आपको value की उम्मीद थी वहाँ प्रॉमिस मिलता है। उस जगह कोई throw नहीं होता, इसीलिए यह सबसे चालाक async bug है।

Node.js भूला हुआ await

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

पहली जाँच सबके लिए पास हो जाती है, और template स्ट्रिंग (string) [object Promise] प्रिंट करती है। @typescript-eslint/no-floating-promises (या ESLint के require-await और no-misused-promises) जैसे linter नियम इन्हें production तक पहुँचने से पहले पकड़ लेते हैं। यह भी देखें कि यहाँ isAllowed(user) एक "floating" प्रॉमिस है जिसका नतीजा कोई नहीं पढ़ता; अगर वह reject होता, तो आपको unhandled rejection मिलता।

hot path में await करना

हर await की कीमत microtask queue का एक चक्कर है। आम कोड में यह दिखता नहीं, पर लाखों छोटे कदम करने वाले तंग लूप में यह जुड़ता जाता है। जिन values के बारे में आप जानते हैं कि वे सादी हैं, उन्हें await न करें, और "बस एहतियात के लिए" synchronous कोड को async functions में न लपेटें।

शैलियाँ मिलाना

बिना वजह एक ही फ़ंक्शन में .then() chains और await न मिलाएँ। await चुनें; .then/.catch को छोटी एक-लाइन वाली चीज़ों के लिए रखें, जैसे fallback value देने के लिए fetchData().catch(() => null)।

Async stack traces

जब कोई error कई await से होकर गुज़रता है, तो V8 एक async stack trace फिर से बनाता है: at async से चिह्नित लाइनें वे functions हैं जो अपने से ऊपर वाले का इंतज़ार कर रहे थे। इसीलिए आधुनिक traces बीच में timers और I/O होने पर भी दिखाते हैं कि किसने किसे कॉल किया।

Node.js async stack trace (जानबूझकर फ़ेल)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

output Error: row 1 is corrupt से शुरू होता है, उसके बाद at readRow (main.mjs:5:9), at async loadReport (main.mjs:9:17) और at async main (main.mjs:14:3) जैसी लाइनें आती हैं, और आखिर में एक file:// loader frame होता है। इन्हें ऊपर से पढ़ें: पहली लाइन वह जगह है जहाँ error बना, और हर at async लाइन एक caller है जो await पर रुका था। trace में सिर्फ़ वे callers होते हैं जो await कर रहे थे: अगर आप किसी फ़ंक्शन को await के बिना कॉल करें (fire and forget), तो वह trace से गायब हो जाता है।

--enable-source-maps दें (हमारा runner पहले से ऐसा करता है) ताकि TypeScript या bundled कोड भी आपकी मूल लाइनों की ओर इशारा करे।

जिस फ़ंक्शन को ज़रूरत न हो, उस पर कभी async न लिखें। बिना await वाला async फ़ंक्शन फिर भी काम करता है, पर वह synchronous throws को rejected प्रॉमिस में छिपा देता है और एक अतिरिक्त microtask खर्च करता है। साथ ही, rejection संभाले बिना async फ़ंक्शन ऐसे APIs को न दें जो return values को अनदेखा करते हैं (event listeners, setInterval, array.forEach), वरना error unhandled rejection बन जाता है।

सबको जोड़कर: एक छोटी समानांतर pipeline

Node.js क्रमिक निर्भरताएँ और समानांतर fan-out

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

असली async कोड का ज़्यादातर आकार यही होता है: एक-दो कदम जो एक-दूसरे पर निर्भर हों, और बीच में एक समानांतर fan-out। अगर आपको सिर्फ़ एक बात याद रखनी है, तो हर await पर यह पूछना याद रखें: क्या अगली लाइन को यह नतीजा चाहिए?

अपनी समझ जाँचें

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. async फ़ंक्शन हमेशा क्या लौटाता है?

    async फ़ंक्शन कॉल करने पर हमेशा प्रॉमिस मिलता है। वह लौटाई गई value के साथ fulfill होता है या throw हुए error के साथ reject होता है।
  2. 2. दो requests एक-दूसरे पर निर्भर नहीं हैं। कौन-सा कोड उन्हें समानांतर चलाता है?

    Promise.all दोनों operations तुरंत शुरू करता है और दोनों का इंतज़ार करता है। बाकी रूप उन्हें एक के बाद एक चलाते हैं।
  3. 3. items.forEach(async (item) => { await save(item); }) saves का इंतज़ार क्यों नहीं करता?

    forEach callback को कॉल करता है और उसकी रिटर्न वैल्यू फेंक देता है, इसलिए वह कभी प्रॉमिस का इंतज़ार नहीं करता। for...of या map के साथ Promise.all इस्तेमाल करें।
  4. 4. try block के अंदर return await query() क्यों लिखें?

    await के बिना pending प्रॉमिस सीधे लौटा दिया जाता है, try block खत्म हो जाता है, और बाद का rejection catch को छोड़कर निकल जाता है।
  5. 5. जब isAllowed async हो और आप उसे await करना भूल जाएँ, तो if (isAllowed(user)) क्या करता है?

    शर्त को एक Promise ऑब्जेक्ट मिलता है, जो हमेशा truthy होता है। जाँच का नतीजा कभी पढ़ा ही नहीं जाता।

सारांश

  • async functions प्रॉमिस लौटाते हैं; await सिर्फ़ मौजूदा फ़ंक्शन को रोकता है और प्रॉमिस को खोलता है या उसका rejection throw करता है।
  • क्रम से await सिर्फ़ निर्भर कदमों के लिए करें; स्वतंत्र काम के लिए Promise.all इस्तेमाल करें।
  • try/catch/finally awaits के पार काम करता है; try के अंदर return await इस्तेमाल करें।
  • for...of क्रमिक है; async callbacks वाला forEach इंतज़ार नहीं करता; map के साथ Promise.all समानांतर है।
  • Top-level await सिर्फ़ ES modules में काम करता है।
  • भूला हुआ await value की जगह truthy प्रॉमिस देता है; floating promises के लिए lint करें।
  • stack traces के at async frames await करने वाले callers की कड़ी दिखाते हैं।

आगे: Concurrency Control और Queues

अपनी प्रगति ट्रैक करें

मुफ़्त अकाउंट बनाएँ, लेसन पूरे के रूप में चिह्नित करें और किसी भी डिवाइस पर वहीं से शुरू करें जहाँ छोड़ा था।