← Back to Swift Course | Chapter 13: Concurrency | Lesson 1 of 6

async/await के Basics

async/await आपके code को किसी धीमी चीज़ का इंतज़ार करते हुए pause होने देता है, बाकी सब कुछ freeze किए बिना, और फिर इसे वहीं से उठाता है जहां यह छोड़ा गया था।
Syntax
swift
func functionName() async -> ReturnType {
    return value
}

func caller() async {
    let result = await functionName()   // suspends until done
}

Declaring an async Function

किसी function के parameter list के बाद async जोड़ना इसे asynchronous चिह्नित करता है, इसे internally await उपयोग करने देते हुए और callers को भी इसे await करने की मांग करते हुए।

उदाहरण: Declaring an async Function

markup
func fetchGreeting() async -> String {
    return "Hello from an async function"
}

let message = await fetchGreeting()
print(message)

Awaiting Multiple async Calls in Sequence

कई await expressions लिखे गए order में एक-एक करके चलते हैं, हर एक अगली line पर जाने से पहले अपना result तैयार होने तक suspend होते हुए।

उदाहरण: Awaiting Multiple async Calls in Sequence

markup
func fetchNumber() async -> Int {
    return 21
}

let first = await fetchNumber()
let second = await fetchNumber()
print("Sum: \(first + second)")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. await keyword के बिना एक async function call करना; किसी async function की हर call को await किया जाना चाहिए।
  2. यह भूल जाना कि इसके अंदर दूसरी async calls को await करने की अनुमति पाने से पहले किसी function को अपने ही signature में async चिह्नित होना चाहिए।
  3. यह मान लेना कि await पूरे program को block करता है; यह सिर्फ current task suspend करता है, बाकी काम को आगे बढ़ने देते हुए।
चैप्टर सारांश
  • async चिह्नित एक function thread को block किए बिना suspend और बाद में resume हो सकता है।
  • किसी async function को call करने के लिए call site पर await keyword चाहिए।
  • await एक potential suspension point मार्क करता है जहां function pause हो सकता है।
  • async/await पुराने completion-handler-based asynchronous code को linear, readable syntax से replace करता है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.