Skip to content

Instantly share code, notes, and snippets.

@mfikes
Last active June 7, 2024 18:33
Show Gist options
  • Save mfikes/f1d06479ee0cf9d2818ccb46418f1b58 to your computer and use it in GitHub Desktop.
Save mfikes/f1d06479ee0cf9d2818ccb46418f1b58 to your computer and use it in GitHub Desktop.
Concurrency comparison Swift async/await and Clojure core.async
(require '[clojure.core.async :refer [go <!]])
(defn fetch-user-id [server]
(go
(if (= server "primary")
97
501)))
(defn fetch-username [server]
(go
(let [user-id (<! (fetch-user-id server))]
(if (= user-id 501)
"John Appleseed"
"Guest"))))
(defn connect-user [server]
(go
(let [user-id-ch (fetch-user-id server)
username-ch (fetch-username server)
greeting (str "Hello " (<! username-ch) ", user ID " (<! user-id-ch))]
(println greeting))))
(go
(connect-user "primary"))
func fetchUserID(from server: String) async -> Int {
if server == "primary" {
97
} else {
501
}
}
func fetchUsername(from server: String) async -> String {
let userID = await fetchUserID(from: server)
if userID == 501 {
return "John Appleseed"
} else {
return "Guest"
}
}
func connectUser(to server: String) async {
async let userID = fetchUserID(from: server)
async let username = fetchUsername(from: server)
let greeting = await "Hello \(username), user ID \(userID)"
print(greeting)
}
Task {
await connectUser(to: "primary")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment