async / wait वादों की तुलना में एसिंक्रोनस कोड लिखने का एक नया तरीका है। एसिंक/वेट के मुख्य लाभ पठनीयता में सुधार और प्रॉमिस चेनिंग से बचाव हैं। वादे लंबे हो सकते हैं, पढ़ने में कठिन हो सकते हैं, और उनमें गहरे निहित कॉलबैक हो सकते हैं जिन्हें डीबग करना मुश्किल हो सकता है।
पहले से हमारे फ़ेच को याद करें।
fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)) .finally(() => console.log('All done'));
एसिंक/प्रतीक्षा का उपयोग करके, कोड को इस तरह दिखने के लिए दोबारा तैयार किया जा सकता है:
async function fetchData() { try { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } finally { console.log('All done'); } } fetchData();
हालाँकि इसमें कोड की कुछ और पंक्तियाँ हो सकती हैं, यह संस्करण पढ़ना आसान है क्योंकि यह एक सामान्य सिंक्रोनस फ़ंक्शन जैसा दिखता है। इसके अतिरिक्त, यदि .then() कथनों के अंदर के कार्य अधिक जटिल होते, तो पठनीयता और डिबगबिलिटी और भी अधिक प्रभावित होती। एसिंक/प्रतीक्षा उदाहरण कहीं अधिक स्पष्ट है।
एक एसिंक/प्रतीक्षा फ़ंक्शन के दो आवश्यक भाग होते हैं: एसिंक और प्रतीक्षा। फ़ंक्शन घोषणा से पहले async कीवर्ड जोड़ा जाता है, और एसिंक्रोनस कार्य शुरू होने पर wait का उपयोग किया जाता है।
आइए इसे एक रेस्तरां से खाना ऑर्डर करने के उदाहरण से स्पष्ट करें:
// Simulate the order process with async/await async function foodOrder() { console.log("Ordering food..."); await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds for food to be prepared return "Your food is ready!"; } // Simulate the eating process function eatFood(order) { console.log(order); // This logs "Your food is ready!" console.log("Enjoying the meal!"); } // Simulate continuing the conversation function continueConversation() { console.log("While waiting, you continue chatting with friends..."); } async function orderFood() { console.log("You've arrived at the restaurant."); const order = await foodOrder(); // Place the order and wait for it to be ready continueConversation(); // Chat while waiting eatFood(order); // Eat the food once it arrives } orderFood();
आउटपुट होगा
You've arrived at the restaurant. Ordering food... While waiting, you continue chatting with friends... Your food is ready! Enjoying the meal!
अस्वीकरण: उपलब्ध कराए गए सभी संसाधन आंशिक रूप से इंटरनेट से हैं। यदि आपके कॉपीराइट या अन्य अधिकारों और हितों का कोई उल्लंघन होता है, तो कृपया विस्तृत कारण बताएं और कॉपीराइट या अधिकारों और हितों का प्रमाण प्रदान करें और फिर इसे ईमेल पर भेजें: [email protected] हम इसे आपके लिए यथाशीघ्र संभालेंगे।
Copyright© 2022 湘ICP备2022001581号-3