async/await के Basics
async/await आपके code को किसी धीमी चीज़ का इंतज़ार करते हुए pause होने देता है, बाकी सब कुछ freeze किए बिना, और फिर इसे वहीं से उठाता है जहां यह छोड़ा गया था।
Syntax
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
func fetchGreeting() async -> String {
return "Hello from an async function"
}
let message = await fetchGreeting()
print(message)
Login to try C/C++/Java/PHP code in the editor
Awaiting Multiple async Calls in Sequence
कई await expressions लिखे गए order में एक-एक करके चलते हैं, हर एक अगली line पर जाने से पहले अपना result तैयार होने तक suspend होते हुए।
उदाहरण: Awaiting Multiple async Calls in Sequence
func fetchNumber() async -> Int {
return 21
}
let first = await fetchNumber()
let second = await fetchNumber()
print("Sum: \(first + second)")
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
awaitkeyword के बिना एकasyncfunction call करना; किसी async function की हर call को await किया जाना चाहिए।- यह भूल जाना कि इसके अंदर दूसरी async calls को
awaitकरने की अनुमति पाने से पहले किसी function को अपने ही signature मेंasyncचिह्नित होना चाहिए। - यह मान लेना कि
awaitपूरे program को block करता है; यह सिर्फ current task suspend करता है, बाकी काम को आगे बढ़ने देते हुए।
चैप्टर सारांश
asyncचिह्नित एक function thread को block किए बिना suspend और बाद में resume हो सकता है।- किसी
asyncfunction को call करने के लिए call site परawaitkeyword चाहिए। 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: