You can invoke async function from normal function by wrapping the asynchronous call inside a task:
func hi() async {
print("hi")
}
func callAsyncHi() {
let task = Task {
await hi()
}
}
This is similar to how you can invoke async methods in java script from synchrnous context, key difference being in Swift you have to explicitly specify it and inside Task you can invoke more than one async methods.
There are certain reasons behind a design like this. Key reason being in Swift all async methods are associated with tasks and support cooperative cancellation.
Swift concurrency uses a cooperative cancellation model. Each task checks whether it has been canceled at the appropriate points in its execution, and responds to cancellation in whatever way is appropriate.
By requiring async keyword Swift keeps track of the dependency chain of async calls and propagates cancellation event when it occurs (While as far as I know promises in JS doesn't support cancellation of promises). In the above code, you can invoke cancellation on task variable by keeping track of it.
Now the second reason, more important in my opinion, is by requiring explicit invocation this makes it easier to review code as I have to check if cancellation for such invocations are properly handled while in case of JS it is harder to pinpoint such misuse.
await hi()to invoke that async function. You can find reasons on why you writeawaitwhen invoking async function here: docs.swift.org/swift-book/LanguageGuide/Concurrency.htmlasync/awaitis new and it suspend the following codes. so when to call async func in non-async function, you need put it in aTaskadvancedswift.com/async-await/…