SkillByAIइंटरैक्टिव संस्करण खोलें →

पाठ 18 / 30

async/await

async और await से पठनीय asynchronous code लिखें और स्वतंत्र calls को parallel चलाएँ।

await रुकता है, ब्लॉक नहीं करता

await, चारों ओर के async फ़ंक्शन को Promise settle होने तक रोकता है — बाकी Node चलता रहता है।

import { readFile } from "node:fs/promises";

async function loadNotes() {
  const data = await readFile("notes.txt", "utf8");
  console.log(data.length, "characters");
}

loadNotes();

Promise.all से समानांतर

एक-एक करके await करना अनुक्रमिक है — साथ चलाने के लिए Promise.all उपयोग करें।

async function loadBoth() {
  const [notes, config] = await Promise.all([
    readFile("notes.txt", "utf8"),
    readFile("config.json", "utf8"),
  ]);
  console.log(notes.length, config.length);
}

त्वरित जाँच: जब कोई फ़ंक्शन किसी Promise का await करता है, तब बाकी Node का क्या होता है?

  • यह पूरी तरह रुक जाता है
  • यह बाकी काम चलाता रहता है
  • यह इवेंट लूप को फिर से शुरू करता है
  • यह error के साथ exit हो जाता है
Answer

यह बाकी काम चलाता रहता है — `await` केवल वर्तमान async फ़ंक्शन को रोकता है — इस बीच इवेंट लूप बाकी इवेंट संभालने के लिए स्वतंत्र रहता है।