You want to fetch user data and then fetch user posts sequentially using async/await. Which code snippet correctly does this?
hard📝 Application Q8 of 15
iOS Swift - Concurrency
You want to fetch user data and then fetch user posts sequentially using async/await. Which code snippet correctly does this?
Alet user = await fetchUser()
let posts = fetchPosts(user.id)
print(posts)
Blet user = fetchUser()
let posts = fetchPosts(user.id)
print(posts)
Clet user = await fetchUser()
let posts = await fetchPosts(user.id)
print(posts)
Dawait let user = fetchUser()
await let posts = fetchPosts(user.id)
print(posts)
Step-by-Step Solution
Solution:
Step 1: Understand sequential async calls
To fetch user then posts, each async call must be awaited before next.
Step 2: Check each option
let user = await fetchUser()
let posts = await fetchPosts(user.id)
print(posts) correctly awaits both calls sequentially. let user = fetchUser()
let posts = fetchPosts(user.id)
print(posts) misses await. await let user = fetchUser()
await let posts = fetchPosts(user.id)
print(posts) uses invalid syntax. let user = await fetchUser()
let posts = fetchPosts(user.id)
print(posts) misses await on second call.
Final Answer:
let user = await fetchUser()
let posts = await fetchPosts(user.id)
print(posts) -> Option C
Quick Check:
await each sequentially [OK]
Quick Trick:Await each async call in order to run sequentially [OK]
Common Mistakes:
Forgetting await on second async call
Using invalid await let syntax
Calling async functions without await
Master "Concurrency" in iOS Swift
9 interactive learning modes - each teaches the same concept differently