Async/प्रतीक्षा का परिचय
Async/await Node.js में एसिंक्रोनस संचालन को संभालने का एक आधुनिक तरीका है, जो वादों पर आधारित है और आपको बेहतर पठनीयता के साथ कोड बनाने की सुविधा देता है।
Node.js 7.6 ES2017 , async/await .
बेहतर पठनीयता
सिंक कोड इस तरह दिखता है
आसान त्रुटि प्रबंधन
प्रयास/पकड़ ब्लॉक का उपयोग करता है
वादों का आधार
वादों पर निर्मित
महत्वपूर्ण नोट:
Async/प्रतीक्षा अनिवार्य रूप से बेहतर पठनीयता सिंटैक्स के साथ वादे हैं। यह आपके कोड को साफ़-सुथरा और रखरखाव में आसान बनाता है।
सिंटैक्स और उपयोग
सिंटैक्स में दो महत्वपूर्ण शब्द शामिल हैं:
async
एक एसिंक्रोनस फ़ंक्शन घोषित करने के लिए उपयोग किया जाता है जो एक वादा लौटाता है
await
किसी वादे का समाधान होने तक ऑपरेशन को निलंबित करने के लिए उपयोग किया जाता है, इसका उपयोग केवल एसिंक फ़ंक्शंस के भीतर ही किया जा सकता है
उदाहरण: बेसिक एसिंक/प्रतीक्षा
async function getData() {
console.log('Starting...');
const result = await someAsyncOperation();
console.log(`Result: ${result}`);
return result;
}
function someAsyncOperation() {
return new Promise(resolve => {
setTimeout(() => resolve('Operation completed'), 1000);
});
}
// Call the async function
getData().then(data => console.log('Final data:', data));
उदाहरण: Async/Await के साथ फ़ाइल ट्रैवर्सल
const fs = require('fs').promises;
async function readFile() {
try {
const data = await fs.readFile('myfile.txt', 'utf8');
console.log(data);
} catch (error) {
console.error('Error reading file:', error);
}
}
readFile();
ट्राई/कैच के साथ त्रुटि प्रबंधन
एसिंक/प्रतीक्षा का एक लाभ यह है कि आप त्रुटि प्रबंधन के लिए पारंपरिक प्रयास/पकड़ ब्लॉक का उपयोग कर सकते हैं, जो आपके कोड की पठनीयता में सुधार करता है।
उदाहरण: Async/Await के साथ त्रुटि प्रबंधन
async function fetchUserData() {
try {
const response = await fetch('https://api.example.com/users/1');
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const user = await response.json();
console.log('User data:', user);
return user;
} catch (error) {
console.error('Error fetching user data:', error);
throw error; // Re-throw the error if needed
}
}
आप विभिन्न स्थितियों के लिए async/await को Promise .catch() के साथ मिला सकते हैं:
// Using catch with an async function
fetchUserData().catch(error => {
console.log('Caught outside of async function:', error.message);
});
वादे समानांतर चल रहे हैं
हालाँकि async/प्रतीक्षा कोड समकालिक दिखता है, कभी-कभी सर्वोत्तम प्रदर्शन के लिए संचालन को समानांतर में चलाने की आवश्यकता होती है।
उदाहरण: अनुक्रमिक और समानांतर संचालन
// Helper function to simulate an API call
function fetchData(id) {
return new Promise(resolve => {
setTimeout(() => resolve(`Data for ID ${id}`), 1000);
});
}
// Sequential operation - takes ~3 seconds
async function fetchSequential() {
console.time('sequential');
const data1 = await fetchData(1);
const data2 = await fetchData(2);
const data3 = await fetchData(3);
console.timeEnd('sequential');
return [data1, data2, data3];
}
// Parallel operation - takes ~1 second
async function fetchParallel() {
console.time('parallel');
const results = await Promise.all([
fetchData(1),
fetchData(2),
fetchData(3)
]);
console.timeEnd('parallel');
return results;
}
// Demo
async function runDemo() {
console.log('Running sequentially...');
const seqResults = await fetchSequential();
console.log(seqResults);
console.log('\nRunning in parallel...');
const parResults = await fetchParallel();
console.log(parResults);
}
runDemo();
Async/प्रतीक्षा बनाम वादे बनाम कॉलबैक
आइए देखें कि एक ही कार्य को विभिन्न अतुल्यकालिक तरीकों से कैसे संभाला जाता है:
कॉलबैक के साथ
function getUser(userId, callback) {
setTimeout(() => {
callback(null, { id: userId, name: 'John' });
}, 1000);
}
function getUserPosts(user, callback) {
setTimeout(() => {
callback(null, ['Post 1', 'Post 2']);
}, 1000);
}
// Using callbacks
getUser(1, (error, user) => {
if (error) {
console.error(error);
return;
}
console.log('User:', user);
getUserPosts(user, (error, posts) => {
if (error) {
console.error(error);
return;
}
console.log('Posts:', posts);
});
});
वादों के साथ
function getUserPromise(userId) {
return new Promise(resolve => {
setTimeout(() => {
resolve({ id: userId, name: 'John' });
}, 1000);
});
}
function getUserPostsPromise(user) {
return new Promise(resolve => {
setTimeout(() => {
resolve(['Post 1', 'Post 2']);
}, 1000);
});
}
// Using promises
getUserPromise(1)
.then(user => {
console.log('User:', user);
return getUserPostsPromise(user);
})
.then(posts => {
console.log('Posts:', posts);
})
.catch(error => {
console.error(error);
});
Async/प्रतीक्षा के साथ
// Using async/await
async function getUserAndPosts() {
try {
const user = await getUserPromise(1);
console.log('User:', user);
const posts = await getUserPostsPromise(user);
console.log('Posts:', posts);
} catch (error) {
console.error(error);
}
}
getUserAndPosts();
| तरीका | फ़ायदे | समस्याएँ |
|---|---|---|
| कॉलबैक |
|
|
| वादे |
|
|
| Async/Await |
|
|
सर्वोत्तम अभ्यास
Node.js async/await , :
याद रखें जब Async फ़ंक्शंस वादे लौटाते हैं
async function myFunction() {
return 'Hello';
}
// This returns a Promise that resolves to 'Hello', not the string 'Hello' directly
const result = myFunction();
console.log(result); // Promise { 'Hello' }
// You need to await it or use .then()
myFunction().then(message => console.log(message)); // Hello
समानांतर संचालन के लिए Promise.all का उपयोग करें
जब संचालन समानांतर में चल सकता है तो प्रदर्शन को बेहतर बनाने के लिए Promise.all का उपयोग करें
त्रुटियों को हमेशा संभालें
एसिंक फ़ंक्शन कॉल में ट्राई/कैच ब्लॉक या चेन .कैच() का उपयोग करें
कॉलबैक के साथ एसिंक/प्रतीक्षा को भ्रमित न करें
util.promisify - -
उदाहरण: कॉलबैक को वादों में परिवर्तित करना
const util = require('util');
const fs = require('fs');
// Convert callback-based function to Promise-based
const readFile = util.promisify(fs.readFile);
async function readFileContents() {
const data = await readFile('file.txt', 'utf8');
return data;
}
सर्वश्रेष्ठ प्रणालियां:
Node.js 14.8.0 ECMAScript (ESM) "- await" , async await .
सारांश
तुल्यकालिक कोड
एसिंक्रोनस कोड सिंक्रोनस कोड जैसा दिखता है
वादों का आधार
वादों पर निर्मित
त्रुटि प्रबंधन का प्रयास/पकड़ें
पारंपरिक त्रुटि प्रबंधन विधियों का उपयोग करता है
समानांतर संचालन
Promise.all
महत्वपूर्ण बिंदु:
- Async/await पठनीयता में उल्लेखनीय सुधार करता है
- वादों पर निर्मित
- ट्राई/कैच के साथ त्रुटि प्रबंधन आसान है
- समानांतर संचालन के लिए Promise.all का उपयोग करें
- याद रखें जब async फ़ंक्शंस वादे लौटाते हैं
अभ्यास
सही कीवर्ड चुनें.
______कुंजी शब्द का उपयोग किसी फ़ंक्शन से पहले किया जाता है जो एक वादा लौटाता है।