async/await के साथ लूप का उपयोग करके एसिंक्रोनस फंक्शन्स को क्रमिक रूप से (एक के बाद एक) चलाएं।
बुनियादी पैटर्न
async function runSequentially(times) {
for (let i = 1; i <= times; i++) {
await asyncTask1(`कॉल ${i} - Task 1`);
await asyncTask2(`कॉल ${i} - Task 2`);
}
}
async function asyncTask1(label) {
return new Promise(resolve => {
setTimeout(() => {
console.log(label);
resolve();
}, 100); // सिम्युलेटेड एसिंक काम
});
}
async function asyncTask2(label) {
return new Promise(resolve => {
setTimeout(() => {
console.log(label);
resolve();
}, 100);
});
}
// चलाएं
runSequentially(3);
आउटपुट
कॉल 1 - Task 1
कॉल 1 - Task 2
कॉल 2 - Task 1
कॉल 2 - Task 2
कॉल 3 - Task 1
कॉल 3 - Task 2
ऐरे के फंक्शन्स पर इटरेट करें
const asyncFunctions = [
() => delay(100).then(() => console.log('Task 1')),
() => delay(100).then(() => console.log('Task 2')),
() => delay(100).then(() => console.log('Task 3'))
];
async function runAllSequentially(functions) {
for (const fn of functions) {
await fn(); // प्रत्येक पूरा होने का इंतजार करें
}
console.log('सभी पूरे हुए');
}
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
runAllSequentially(asyncFunctions);
पैरालेल (समानांतर) बनाम सीक्वेंशियल
// ❌ सीक्वेंशियल - धीमा (कुल समय = योग)
for (const fn of functions) {
await fn();
}
// ✅ पैरालेल - तेज़ (कुल समय = अधिकतम)
await Promise.all(functions.map(fn => fn()));
// ✅ बैच्ड - बैच में समानांतर
async function runInBatches(functions, batchSize = 2) {
for (let i = 0; i < functions.length; i += batchSize) {
const batch = functions.slice(i, i + batchSize);
await Promise.all(batch.map(fn => fn()));
}
}
रिटर्न वैल्यूज़ के साथ
async function fetchUserData(userIds) {
const results = [];
for (const id of userIds) {
const data = await fetch(`/api/user/${id}`).then(r => r.json());
results.push(data);
console.log(`यूजर ${id} लोडेड`);
}
return results;
}
// या map के साथ (यदि क्रम महत्वपूर्ण नहीं)
async function fetchAllParallel(userIds) {
const promises = userIds.map(id =>
fetch(`/api/user/${id}`).then(r => r.json())
);
return Promise.all(promises);
}
चलाने का तरीका
node async-iteration.js
मुख्य बिंदु
for...ofलूपawaitके साथ सही काम करता हैforEachawaitके साथ काम नहीं करता (कॉलबैक async नहीं होता)map+Promise.all= पैरालेलfor...of+await= सीक्वेंशियल