🌐 Detecting your location…
📢 Advertisement — Configure AdSense in Appearance → Customize → AdSense Settings

जावास्क्रिप्ट एसिंक/प्रतीक्षा: संपूर्ण 2026 गाइड

⏱️4 min read  ·  858 words



JavaScript Async/Await: The Complete 2026 Guide

टेकपल्स संपादकीय टीम
टेक लेखक · 28 मई, 2026
📅 28 मई, 2026⏱ 13 मिनट पढ़ें📂 प्रोग्रामिंग🏷 जावास्क्रिप्ट · एसिंक-प्रतीक्षा · वादे

Async/प्रतीक्षा क्या है?

Async/प्रतीक्षाएसिंक्रोनस ऑपरेशंस के साथ काम करने के लिए जावास्क्रिप्ट का सबसे साफ सिंटैक्स है – नेटवर्क अनुरोध, फ़ाइल I/O, डेटाबेस क्वेरी, टाइमर। ES2017 (ES8) में पेश किया गया, यह एसिंक कोड को सिंक्रोनस कोड की तरह पढ़ता है:

  • async– किसी फ़ंक्शन को अतुल्यकालिक के रूप में चिह्नित करता है; हमेशा एक वादा लौटाता है
  • await– एक एसिंक फ़ंक्शन के अंदर निष्पादन को तब तक रोक देता है जब तक कि कोई वादा पूरा नहीं हो जाता
मुख्य अंतर्दृष्टि:async/await वादों के शीर्ष पर बनाया गया है।await somePromise|||| के बराबर है . समान तंत्र, स्वच्छ वाक्यविन्यास।somePromise.then(result => ...)वादे पहले: फाउंडेशन

Async/प्रतीक्षा से पहले, आपने वादों को

के साथ जोड़ा है . इसे समझने से async/प्रतीक्षा पर क्लिक होता है:.then()📋कॉपी

// Promise chain — works, but nests deeply
fetch('https://api.example.com/users/1')
  .then(response => response.json())
  .then(user => fetch('https://api.example.com/posts?userId=' + user.id))
  .then(response => response.json())
  .then(posts => console.log(posts))
  .catch(error => console.error('Failed:', error));

// Same logic with async/await — flat and readable
async function getUserPosts(userId) {
  const userRes = await fetch('https://api.example.com/users/' + userId);
  const user = await userRes.json();
  const postsRes = await fetch('https://api.example.com/posts?userId=' + user.id);
  const posts = await postsRes.json();
  return posts;
}

📋कॉपी

async function getUser(id) {
  const response = await fetch('https://jsonplaceholder.typicode.com/users/' + id);
  if (!response.ok) throw new Error('HTTP error: ' + response.status);
  return response.json();
}

const user = await getUser(1);
console.log(user.name); // "Leanne Graham"

फ़ंक्शन हमेशा एक वादा लौटाता है।asyncकेवल async फ़ंक्शंस के अंदर काम करता है। यदि कोई प्रतीक्षित वादा अस्वीकार कर दिया जाता है, तो यह एक त्रुटिपूर्ण त्रुटि के रूप में प्रचारित होता है।awaitप्रयास/पकड़ के साथ त्रुटि प्रबंधन

📋कॉपी

async function fetchUserData(userId) {
  try {
    const response = await fetch('/api/users/' + userId);
    if (!response.ok) throw new Error('Server error: ' + response.status);
    return await response.json();
  } catch (error) {
    if (error.name === 'TypeError') {
      console.error('Network error:', error.message);
    } else {
      console.error('API error:', error.message);
    }
    return null;
  }
}

// Per-await error handling
async function loadDashboard() {
  const user   = await fetchUserData(1).catch(() => null);
  const stats  = await fetchStats().catch(() => ({ views: 0 }));
  const alerts = await fetchAlerts().catch(() => []);
  return { user, stats, alerts };
}

अनुक्रमिक प्रतीक्षाएँ एक-एक करके चलती हैं।

का प्रयोग करें एक साथ कई वादे करना:Promise.all()📋कॉपी

// ❌ Sequential — 3 seconds total (1s + 1s + 1s)
async function loadSequential() {
  const users  = await fetchUsers();   // waits 1s
  const posts  = await fetchPosts();   // waits another 1s
  const photos = await fetchPhotos();  // waits another 1s
  return { users, posts, photos };
}

// ✅ Parallel — ~1 second total (all fire at once)
async function loadParallel() {
  const [users, posts, photos] = await Promise.all([
    fetchUsers(),
    fetchPosts(),
    fetchPhotos()
  ]);
  return { users, posts, photos };
}

// Promise.allSettled — get results even if some fail
async function loadWithFallbacks() {
  const results = await Promise.allSettled([fetchUsers(), fetchPosts(), fetchPhotos()]);
  return results.map(r => r.status === 'fulfilled' ? r.value : null);
}

// Promise.race — first wins (timeout pattern)
async function fetchWithTimeout(url, ms = 5000) {
  const timeout = new Promise((_, reject) =>
    setTimeout(() => reject(new Error('Request timed out')), ms)
  );
  return Promise.race([fetch(url), timeout]);
}

📋कॉपी

const userIds = [1, 2, 3, 4, 5];

// ❌ forEach DOES NOT await — requests fire but nothing waits
userIds.forEach(async (id) => {
  const user = await fetchUser(id); // fires immediately without waiting
  console.log(user.name);
});

// ✅ for...of — sequential (each awaits before next starts)
for (const id of userIds) {
  const user = await fetchUser(id);
  console.log(user.name);
}

// ✅ Promise.all + map — parallel (all fire simultaneously)
const users = await Promise.all(userIds.map(id => fetchUser(id)));
users.forEach(u => console.log(u.name));

// ✅ Batched parallel (avoid overwhelming the server)
async function batchProcess(ids, batchSize = 5) {
  const results = [];
  for (let i = 0; i < ids.length; i += batchSize) {
    const batch = ids.slice(i, i + batchSize);
    const batchResults = await Promise.all(batch.map(id => fetchUser(id)));
    results.push(...batchResults);
  }
  return results;
}

एसिंक आईआईएफई

📋कॉपी

// Async IIFE — top-level await not available? Use this
(async () => {
  const config = await loadConfig();
  await startServer(config);
  console.log('Server running on port', config.port);
})();

📋कॉपी

async function* streamLargeDataset(url) {
  let page = 1;
  while (true) {
    const response = await fetch(url + '?page=' + page);
    const data = await response.json();
    if (!data.items.length) break;
    yield data.items;
    page++;
  }
}

// Consume with for-await-of
for await (const items of streamLargeDataset('/api/records')) {
  processItems(items);
}

के साथ पुनः प्रयास करें 📋कॉपी

async function fetchWithRetry(url, options = {}, retries = 3, backoff = 1000) {
  try {
    const res = await fetch(url, options);
    if (!res.ok && res.status >= 500 && retries > 0) {
      await new Promise(r => setTimeout(r, backoff));
      return fetchWithRetry(url, options, retries - 1, backoff * 2);
    }
    return res;
  } catch (err) {
    if (retries > 0) {
      await new Promise(r => setTimeout(r, backoff));
      return fetchWithRetry(url, options, retries - 1, backoff * 2);
    }
    throw err;
  }
}

भूल जाना

  • — आपको एक लंबित वादा मिलता है, मूल्य नहींawaitप्रत्येक के लिए async
  • — उपयोगयाfor...ofइसके बजायPromise.allजब समानांतर संभव हो तो अनुक्रमिक प्रतीक्षा करता है
  • – अनावश्यक क्रमबद्धता प्रदर्शन को खत्म कर देती हैनिगलने में त्रुटियाँ
  • – खाली कैच ब्लॉक बग छिपाते हैं। लॉग करें या पुनः फेंकें.📋कॉपी

// ❌ Missing await — user is a Promise, not an object
async function broken() {
  const user = fetchUser(1);   // missing await!
  console.log(user.name);      // undefined — user is a Promise
}

// ✅ Fixed
async function fixed() {
  const user = await fetchUser(1);
  console.log(user.name);      // "Leanne Graham"
}

टाइमआउट और त्रुटि प्रबंधन के साथ एक उत्पादन-तैयार एपीआई क्लाइंट:

📋कॉपी

class ApiClient {
  constructor(baseUrl, options = {}) {
    this.baseUrl = baseUrl;
    this.timeout = options.timeout || 10000;
  }

  async request(path, options = {}) {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), this.timeout);
    try {
      const response = await fetch(this.baseUrl + path, {
        ...options,
        signal: controller.signal,
        headers: { 'Content-Type': 'application/json', ...options.headers }
      });
      clearTimeout(timeoutId);
      if (!response.ok) {
        const err = await response.json().catch(() => ({}));
        throw Object.assign(new Error(err.message || 'HTTP ' + response.status), {
          status: response.status, body: err
        });
      }
      return response.json();
    } catch (error) {
      clearTimeout(timeoutId);
      if (error.name === 'AbortError') throw new Error('Request timed out');
      throw error;
    }
  }

  async get(path)        { return this.request(path); }
  async post(path, body) { return this.request(path, { method: 'POST', body: JSON.stringify(body) }); }
}

const api = new ApiClient('https://api.example.com', { timeout: 8000 });
const user = await api.get('/users/1');

Async/await सबसे महत्वपूर्ण आधुनिक JS पैटर्न में से एक है। अन्वेषण करें

टाइपस्क्रिप्ट एसिंक पैटर्न को और भी सुरक्षित क्यों बनाता है, या जांचेंसभी प्रोग्रामिंग गाइडअधिक गहरे गोता लगाने के लिए.अक्सर पूछे जाने वाले प्रश्न

एसिंक/प्रतीक्षा क्या है?

वादों पर वाक्यात्मक चीनी।

एक फ़ंक्शन async को चिह्नित करता है;asyncइसे तब तक रोकें जब तक कि कोई वादा पूरा न हो जाए। एसिंक कोड को सिंक कोड की तरह पढ़ने योग्य बनाता है।awaitएसिंक/प्रतीक्षा और वादों के बीच अंतर?

समान तंत्र, स्वच्छ वाक्यविन्यास। पठनीयता के लिए async/प्रतीक्षा का उपयोग करें;

के लिए कच्चे वादों का उपयोग करें ,Promise.all().Promise.race()त्रुटियों को कैसे संभालें?

प्रयास/पकड़ ब्लॉक का उपयोग करें। या जोड़ें

व्यक्तिगत प्रतीक्षित वादों के लिए।.catch()समानांतर में ऑपरेशन कैसे चलाएं?

– सभी एक साथ फायर करते हैं।

await Promise.all([p1, p2, p3])प्रत्येक के लिए async/प्रतीक्षा करें?

नहीं – forEach async कॉलबैक को अनदेखा करता है।

का प्रयोग करें याfor...of.Promise.all(arr.map(async x => ...))शीर्ष-स्तरीय प्रतीक्षा क्या है?

ES2022 – एसिंक रैपर के बिना मॉड्यूल शीर्ष स्तर पर प्रतीक्षा का उपयोग करें। केवल ईएस मॉड्यूल।

ES2022 — use await at module top level without async wrapper. ES modules only.

✍️ Leave a Comment

Your email address will not be published. Required fields are marked *

🌐 Read in:🇬🇧 English🇩🇪 Deutsch🇧🇷 Português🇸🇦 العربية🇮🇳 हिन्दी🇧🇩 বাংলা